'use strict';

angular.module('BaseControl')
.directive("datagrid", ['$compile', 'BaseConfig', 'BaseEnum', 'BaseClass', 'BaseFunction', 'BaseExcel', 'EntityService', 
    function($compile, BaseConfig, BaseEnum, BaseClass, BaseFunction, BaseExcel, EntityService) {
    return {
        restrict: "E",
        scope: {
            module: '=',
            rowdblclick: '&',       //双击表格行后
            rowchange: '&',         //行改变后
            cellvaluechange: '&',   //单元格值发生变化后
            cellclick: '&',     //点击单元格前
            addrow: '&',        //新增行后
            deleterow: '&',     //删除行后
            order: '&',          //排序完成后
            turnpage: '&',       //翻页之后
            isedit: '@?',
            isadd: '@?',
            ismodify: '@?',
            isdelete: '@?'
        },
        templateUrl:        // 替换HTML (使用scope中的变量)
            'modules/Base/client/views/DataGrid.html',
        replace: true,          // 使用模板替换原始标记
        transclude: true,       // 不复制原始HTML内容
        controller: ['$scope', function ($scope) {
            var ctrl = this;
            ctrl.scope = $scope;

            $scope.Columns = [];
            $scope.EventManage = new BaseClass.Event();
            $scope.Checked = {IsCheckedAll : false};      //左上角全选按钮绑定值，这里必须是对象的属性，因为CheckBox控件的value的值绑定问题
            $scope.CheckColumn = {Width: '50px'};     //定义CheckBox列的宽度以及
            $scope.Edit = {
                get IsEdit(){
                    if($scope.isedit && $scope.isedit.toLowerCase().trim() == 'false'){
                        return false;
                    }
                    else{
                        return true;
                    }
                },
                get IsAdd(){
                    if($scope.isadd && $scope.isadd.toLowerCase().trim() == 'false'){
                        return false;
                    }
                    else{
                        return true;
                    }
                },
                get IsModify(){
                    if($scope.ismodify && $scope.ismodify.toLowerCase().trim() == 'false'){
                        return false;
                    }
                    else{
                        return true;
                    }
                },
                get IsDelete(){
                    if($scope.isdelete && $scope.isdelete.toLowerCase().trim() == 'false'){
                        return false;
                    }
                    else{
                        return true;
                    }
                }
            };

            var getRecordById = function(id){
                var records = $scope.module.Records
                for(var i=0; i<records.length; i++){
                    if(records[i]._id == id){
                        return records[i];
                    }
                }
                return null;
            };
            $scope.getRowIndex = function(id){
                for(var i=0; i<$scope.Dom._BodyElement.rows.length; i++){
                    if($scope.Dom._BodyElement.rows[i].getAttribute('key') == id){
                        return i;
                    }
                }
                return -1;
            };
            $scope.getCellIndex = function(columnName){
                for(var i=0; i<$scope.Dom._HeadElement.rows[0].cells.length; i++){
                    if($scope.Dom._HeadElement.rows[0].cells[i].getAttribute('ValueField') == columnName){
                        return i;
                    }
                }
                return -1;
            };
            $scope.setCellText = function(rowIndex, cellIndex, text){
                $scope.Dom._BodyElement.rows[rowIndex].cells[cellIndex].children[0].setAttribute("Title", text)
                $scope.Dom._BodyElement.rows[rowIndex].cells[cellIndex].children[0].innerHTML = text;
            };
            $scope.btnAdd = function(){
                var newRecord = $scope.module.add();
                $scope.addRowHtml(newRecord);
                $scope.RecordCount++;
                $scope.PageNum = 0;

                $scope.addrow({record: newRecord});
            };
            $scope.batchEdit = function(){
                alert("批量编辑");
            };

            //全选\取消全选
            $scope.checkedAllClick = function(){
                for(var i=0; i<$scope.Dom._BodyLeftElement.rows.length; i++) {
                    getRecordById($scope.Dom._BodyLeftElement.rows[i].getAttribute('key')).IsSelected = event.srcElement.checked;
                    $scope.Dom._BodyLeftElement.rows[i].cells[0].children[0].children[0].checked = event.srcElement.checked
                }
            };
            //行选择\取消选择
            $scope.checkedLineClick = function() {
                $scope.module.FocusedRecord.IsSelected = event.srcElement.checked;

                if($scope.module.FocusedRecord.IsSelected){
                    var isAllSelected = true;
                    for (var i = 0; i < $scope.Dom._BodyElement.rows.length; i++) {
                        if (!getRecordById($scope.Dom._BodyLeftElement.rows[i].getAttribute('key')).IsSelected) {
                            isAllSelected = false;
                            break;
                        }
                    }
                    if ($scope.Checked.IsCheckedAll != isAllSelected) {
                        $scope.Checked.IsCheckedAll = isAllSelected;
                    }
                }
                else{
                    if ($scope.Checked.IsCheckedAll != isAllSelected) {
                        $scope.Checked.IsCheckedAll = false;
                    }
                }
            };

            $scope.rowClick = function() {
                var domRow = event.srcElement;
                while (domRow.tagName.toLowerCase() != "tr") {
                    domRow = domRow.parentNode;
                }
                var currentLineID = domRow.getAttribute('key');

                //如果不是行触发，而是行的子元素触发的，则不用处理，比如：日历控件里面就带有tr元素
                if(currentLineID == null){
                    return;
                }

                //校验是否是子Grid触发，因为参照控件弹出的Grid是在主Grid的TD中，也会触发主Grid的RowClick事件
                var gridElement = domRow.parentNode.parentNode.parentNode.parentNode.parentNode;
                while(gridElement.tagName.toLowerCase() != 'div' || gridElement.getAttribute('class') == null || 
                    gridElement.getAttribute('class').toLowerCase() != 'datagriddiv'){
                    gridElement = gridElement.parentNode;
                }
                if(gridElement != $scope.Dom._tableDiv){
                    return;
                }

                if($scope.module.FocusedRecord == null || $scope.module.FocusedRecord._id != currentLineID) {
                    if($scope.module.FocusedRecord != null){
                        var oldRowIndex = $scope.getRowIndex($scope.module.FocusedRecord._id);

                        if($scope.IsSelect) {
                            $scope.Dom._BodyLeftElement.rows[oldRowIndex].removeAttribute('style');
                        }
                        $scope.Dom._BodyElement.rows[oldRowIndex].removeAttribute('style');
                        if($scope.Edit.IsEdit && ($scope.Edit.IsAdd || $scope.Edit.IsDelete)) {
                            $scope.Dom._BodyRightElement.rows[oldRowIndex].removeAttribute('style');
                        }
                    }

                    $scope.module.FocusedRecord = getRecordById(currentLineID);
                    if($scope.IsSelect) {
                        $scope.Dom._BodyLeftElement.rows[domRow.rowIndex].style.backgroundColor = '#FAEBB2';
                    }
                    $scope.Dom._BodyElement.rows[domRow.rowIndex].style.backgroundColor = '#FAEBB2';
                    if($scope.Edit.IsEdit && ($scope.Edit.IsAdd || $scope.Edit.IsDelete)) {
                        $scope.Dom._BodyRightElement.rows[domRow.rowIndex].style.backgroundColor = '#FAEBB2';
                    }
                    $scope.rowchange();
                }
            };
            $scope.cellClick = function(){
                if($scope.Edit.IsEdit && $scope.Edit.IsModify) {
                    var srcElem = event.srcElement;
                    while(srcElem){
                        if(srcElem.tagName.toLowerCase() == 'td'){
                            break;
                        }
                        else{
                            srcElem = srcElem.parentNode;
                        }
                    }
                    srcElem = srcElem.children[0];

                    if (srcElem.tagName.toLowerCase() == "div") {
                        var column = $scope.Columns[srcElem.parentNode.cellIndex];
                        var isEdit = $scope.cellclick({columnName: column.scope.ValueField});
                        if(isEdit == undefined || isEdit.constructor != Boolean){
                            isEdit = column.scope.IsEdit;
                        }
                        if (isEdit) {
                            var record = $scope.module.FocusedRecord;
                            if(column.scope.ValueField.indexOf(".") >= 0){
                                var fields = column.scope.ValueField.split(".");
                                var strEvalField = "record";
                                //补齐父对象，不然会报父对象undefined
                                for(var i=0; i<fields.length - 1; i++){
                                    strEvalField += "." + fields[i];
                                    var parentObj = eval(strEvalField);
                                    if(parentObj == undefined || parentObj == null){
                                        eval(strEvalField + " = {};");
                                    }
                                }
                            }

                            column.scope.value = record[column.scope.ValueField];
                            srcElem.style.display = 'none';
                            var inputBox;

                            if(column.scope.ControllType == BaseEnum.ControllType.NumberBox){
                                column.scope.setBoxRound();
                                inputBox = column.Element.children[0];
                                srcElem.parentNode.appendChild(inputBox);
                                window.setTimeout(function () {
                                    inputBox.focus();
                                }, 1);
                            }
                            else if(column.scope.ControllType == BaseEnum.ControllType.PercentBox){
                                column.scope.setBoxRound();
                                inputBox = column.Element.children[0];
                                srcElem.parentNode.appendChild(inputBox);
                                window.setTimeout(function () {
                                    inputBox.focus();
                                }, 1);
                            }
                            else if(column.scope.ControllType == BaseEnum.ControllType.Calendar){
                                column.scope.CurrentCell = srcElem.parentNode;
                                window.setTimeout(function () {
                                    inputBox = column.Element.children[0];
                                    srcElem.parentNode.appendChild(inputBox);

                                    window.setTimeout(function () {
                                        inputBox.children[0].focus();
                                    }, 1);
                                }, 1);
                            }
                            else if(column.scope.ControllType == BaseEnum.ControllType.Refer){
                                inputBox = column.Element.children[0];
                                column.scope.Element = inputBox;        //因为参照列获取不到参照控件
                                srcElem.parentNode.appendChild(inputBox);
                                window.setTimeout(function () {
                                    inputBox.children[0].children[0].focus();
                                }, 100);
                            }
                            else {
                                inputBox = column.Element.children[0];
                                srcElem.parentNode.appendChild(inputBox);
                                window.setTimeout(function () {
                                    inputBox.focus();
                                }, 1);
                            }
                            column.scope.$digest();
                        }
                    }
                }
            };
            $scope.keyDown = function(){
                var tdElement = event.srcElement;
                while(tdElement){
                    if(tdElement.tagName.toLowerCase() == 'td'){
                        break;
                    }
                    tdElement = tdElement.parentNode;
                }
                if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40){
                    var cellIndex = tdElement.cellIndex;
                    var rowIndex = tdElement.parentNode.rowIndex;
                    var replyDiv = null;
                    if(event.keyCode == 13) {
                        var isFindNextEditColumn = false;
                        if (cellIndex < $scope.Dom._BodyElement.rows[rowIndex].cells.length - 1) {
                            for (var i = cellIndex + 1; i < $scope.Dom._BodyElement.rows[rowIndex].cells.length; i++) {
                                if ($scope.Columns[i].scope.IsEdit && $scope.Columns[i].scope.IsDisplay) {
                                    isFindNextEditColumn = true;
                                    replyDiv = $scope.Dom._BodyElement.rows[rowIndex].cells[i].children[0];
                                    break;
                                }
                            }
                        }
                        if (!isFindNextEditColumn) {
                            if (rowIndex < $scope.Dom._BodyElement.rows.length - 1) {
                                for (var i = 0; i < $scope.Dom._BodyElement.rows[rowIndex + 1].cells.length; i++) {
                                    if ($scope.Columns[i].scope.IsEdit && $scope.Columns[i].scope.IsDisplay) {
                                        replyDiv = $scope.Dom._BodyElement.rows[rowIndex + 1].cells[i].children[0];
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else if(event.keyCode == 38) {
                        if(rowIndex > 0){
                            if ($scope.Columns[cellIndex].scope.IsEdit && $scope.Columns[cellIndex].scope.IsDisplay) {
                                replyDiv = $scope.Dom._BodyElement.rows[rowIndex - 1].cells[cellIndex].children[0];

                                //$scope.Dom._tableDiv.scrollTop = $scope.Dom._tableDiv.scrollTop - 36;
                            }
                        }
                    }
                    else if(event.keyCode == 40) {
                        if(rowIndex < $scope.Dom._BodyElement.rows.length - 1){
                            if ($scope.Columns[cellIndex].scope.IsEdit && $scope.Columns[cellIndex].scope.IsDisplay) {
                                replyDiv = $scope.Dom._BodyElement.rows[rowIndex + 1].cells[cellIndex].children[0];

                                //$scope.Dom._tableDiv.scrollTop = $scope.Dom._tableDiv.scrollTop + 36;
                            }
                        }
                    }

                    if(replyDiv != null){
                        event.srcElement.blur();

                        //滚动条位置处理开始
                        var scrollYwidth = $scope.Dom._tableDiv.offsetWidth - $scope.Dom._tableDiv.clientWidth - 2;     //垂直滚动条的宽度
                        var scrollXwidth = $scope.Dom._tableDiv.offsetHeight - $scope.Dom._tableDiv.clientHeight - 2;   //水平滚动条的宽度
                        if(replyDiv.getBoundingClientRect().bottom > $scope.Dom._tableDiv.getBoundingClientRect().bottom - scrollXwidth){
                            $scope.Dom._tableDiv.scrollTop += replyDiv.getBoundingClientRect().bottom - ($scope.Dom._tableDiv.getBoundingClientRect().bottom - scrollXwidth) + 4;
                        }
                        else if(replyDiv.getBoundingClientRect().top < $scope.Dom._HeadElement.getBoundingClientRect().bottom){
                            $scope.Dom._tableDiv.scrollTop -= $scope.Dom._HeadElement.getBoundingClientRect().bottom - replyDiv.getBoundingClientRect().top + 2;
                        }

                        if(replyDiv.getBoundingClientRect().right > $scope.Dom._tableDiv.getBoundingClientRect().right - scrollYwidth){
                            $scope.Dom._tableDiv.scrollLeft += replyDiv.getBoundingClientRect().right - ($scope.Dom._tableDiv.getBoundingClientRect().right - scrollYwidth) + 3;
                        }
                        else if(replyDiv.getBoundingClientRect().left < $scope.Dom._BodyLeftElement.getBoundingClientRect().right){
                            $scope.Dom._tableDiv.scrollLeft = replyDiv.getBoundingClientRect().left - $scope.Dom._BodyElement.getBoundingClientRect().left;
                        }
                        //滚动条位置处理结束
                        replyDiv.click();
                    }
                    else{
                        //目前Chrome对表格不支持keydown
                        if(event.keyCode == 38) {
                            if(rowIndex > 0){
                                $scope.Dom._BodyElement.rows[rowIndex - 1].click();
                            }
                        }
                        else{
                            if(rowIndex < $scope.Dom._BodyElement.rows.length - 1){
                                $scope.Dom._BodyElement.rows[rowIndex + 1].click();
                            }
                        }
                    }
                }
            };

            $scope.addRow = function(){
                var newRecord;
                var rowIndex;
                if($scope.module.FocusedRecord != null) {
                    var focusedRecordIndex = $scope.module.getRecordIndex($scope.module.FocusedRecord);
                    for(var i=0; i< $scope.Dom._BodyElement.rows.length; i++){
                        if($scope.Dom._BodyElement.rows[i].getAttribute('key') == $scope.module.FocusedRecord._id){
                            rowIndex = i;
                            break;
                        }
                    }
                    if(focusedRecordIndex == $scope.module.Records.length - 1){
                        newRecord = $scope.module.add();
                    }
                    else {
                        newRecord = $scope.module.add(focusedRecordIndex + 1);
                    }
                    $scope.RecordCount++;

                    if(rowIndex == $scope.module.PageSize - 1){
                        $scope.nextPage();
                    }
                    else{
                        $scope.addRowHtml(newRecord, rowIndex + 1);
                        if($scope.Dom._BodyElement.rows.length > $scope.module.PageSize){
                            $scope.deleteRowHtml($scope.module.PageSize);
                        }
                    }
                }
                else{
                    newRecord = $scope.module.add(newRecord);
                    $scope.addRowHtml(newRecord);
                    $scope.RecordCount++;
                }                

                $scope.addrow({record: newRecord});
            };
            //删除记录以及对应的行
            var rowDelete = function(record){
                var rowIndex = $scope.getRowIndex(record._id);

                if(record == $scope.module.FocusedRecord){
                    $scope.module.FocusedRecord = null;
                }
                $scope.module.deleteRecord(record);

                if(rowIndex >= 0){
                    $scope.deleteRowHtml(rowIndex);
                    if($scope.PageNum < $scope.PageCount - 1){
                        var lastRecord = $scope.module.Records[($scope.PageNum + 1) * $scope.module.PageSize - 1];
                        $scope.addRowHtml(lastRecord);
                    }

                    if($scope.Dom._BodyElement.rows.length == 0 && $scope.PageNum > 0){
                        $scope.prePage();
                    }
                }
                $scope.RecordCount--;
            };
            $scope.deleteRow = function(){
                var focusedRecord = $scope.module.FocusedRecord;
                rowDelete($scope.module.FocusedRecord);
                
                $scope.deleterow({record: focusedRecord});
            };
            $scope.batchDelete = function(){
                var records = $scope.module.SelectedRecords;
                for(var i=0; i<records.length; i++){
                    rowDelete(records[i]);
                };
            };
            $scope.addColumn = function(columnScope, element){
                var column = {
                    scope: columnScope,
                    Element: element
                };
                $scope.Columns.push(column);

                if(columnScope.ControllType != BaseEnum.ControllType.Html && columnScope.ValueField.indexOf(".")){
                    var listenerColumn = columnScope.ValueField.split(".")[0];
                    $scope.EventManage.addListener("onChange_" + listenerColumn, function(){
                        var focusedRecord = $scope.module.FocusedRecord;
                        var cellValue = null;
                        var cellText = null;
                        try{
                            if(columnScope.ControllType == BaseEnum.ControllType.TextBox){
                                cellValue = eval("focusedRecord." + columnScope.ValueField);
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.NumberBox){
                                cellValue = columnScope.Round.formatNumber(eval("focusedRecord." + columnScope.ValueField));
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.PercentBox){
                                cellValue = columnScope.Round.formatNumber(eval("focusedRecord." + columnScope.ValueField));
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.CheckBox){
                                cellValue = eval("focusedRecord." + columnScope.ValueField);
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.Calendar){
                                cellValue = eval("focusedRecord." + columnScope.ValueField);
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.Refer){
                                cellValue = eval("focusedRecord." + columnScope.ValueField);
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.DropDownList){
                                cellValue = parseInt(eval("focusedRecord." + columnScope.ValueField));
                            }
                        }
                        catch(e){
                            cellValue = null;
                        }

                        if(cellValue == undefined || cellValue == null  || cellValue == ""){
                            cellText = "&nbsp";
                        }
                        else{
                            if(columnScope.ControllType == BaseEnum.ControllType.TextBox){
                                cellText = cellValue;
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.NumberBox){
                                cellText = cellValue.toString();
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.PercentBox){
                                cellText = columnScope.Round.formatPercent(cellValue);
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.CheckBox){
                                if(!cellValue){
                                    cellText = "&nbsp";
                                }
                                else{
                                    cellText = '<div class="Hook"/>';
                                }
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.Calendar){
                                if(cellValue.constructor == String){
                                    cellText = BaseFunction.dateTimeToString(new Date(cellValue), columnScope.Type);
                                }
                                else if(cellValue.constructor == Date){
                                    cellText = BaseFunction.dateTimeToString(cellValue, columnScope.Type);
                                }
                                else{
                                    cellText = "&nbsp";
                                }
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.Refer){
                                try{
                                    cellText = eval("cellValue." + columnScope.TextField);
                                }
                                catch(e){
                                    cellText = "&nbsp";
                                }
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.DropDownList){
                                cellText = "&nbsp";
                                for(var option in columnScope.enum){
                                    if(columnScope.enum[option].Value == cellValue){
                                        cellText = columnScope.enum[option].Text;
                                        break;
                                    }
                                }
                            }
                            else{
                                cellText = "&nbsp";
                            }
                        }
                        
                        var rowIndex = $scope.getRowIndex(focusedRecord._id);
                        var cellIndex = $scope.getCellIndex(columnScope.ValueField);
                        $scope.setCellText(rowIndex, cellIndex, cellText);
                    });
                }
                if(columnScope.ControllType != BaseEnum.ControllType.Html && columnScope.BindField.length > 0){
                    var listenerColumn = columnScope.BindField;
                    if(listenerColumn.split(".").length > 0){
                        listenerColumn = listenerColumn.split(".")[0];
                    }
                    $scope.EventManage.addListener("onChange_" + listenerColumn, function(){
                        var focusedRecord = $scope.module.FocusedRecord;
                        var cellValue = null;
                        var cellText = null;
                        try{
                            if(columnScope.ControllType == BaseEnum.ControllType.TextBox){
                                cellValue = eval("focusedRecord." + columnScope.BindField);
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.NumberBox){
                                cellValue = columnScope.Round.formatNumber(eval("focusedRecord." + columnScope.BindField));
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.PercentBox){
                                cellValue = columnScope.Round.formatNumber(eval("focusedRecord." + columnScope.BindField));
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.CheckBox){
                                cellValue = eval("focusedRecord." + columnScope.BindField);
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.Calendar){
                                cellValue = eval("focusedRecord." + columnScope.BindField);
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.Refer){
                                cellValue = eval("focusedRecord." + columnScope.BindField);
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.DropDownList){
                                cellValue = parseInt(eval("focusedRecord." + columnScope.BindField));
                            }
                        }
                        catch(e){
                            cellValue = null;
                        }

                        var oldValue;
                        try{
                            oldValue = eval("focusedRecord." + columnScope.ValueField);
                            eval("focusedRecord." + columnScope.ValueField + "=cellValue");
                        }
                        catch(e){
                            oldValue = null;
                            cellValue = null;
                        }                        

                        if(cellValue == undefined || cellValue == null  || cellValue == ""){
                            cellText = "&nbsp";
                        }
                        else{
                            if(columnScope.ControllType == BaseEnum.ControllType.TextBox){
                                cellText = cellValue;
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.NumberBox){
                                cellText = cellValue.toString();
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.PercentBox){
                                cellText = columnScope.Round.formatPercent(cellValue);
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.CheckBox){
                                if(!cellValue){
                                    cellText = "&nbsp";
                                }
                                else{
                                    cellText = '<div class="Hook"/>';
                                }
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.Calendar){
                                if(cellValue.constructor == String){
                                    cellText = BaseFunction.dateTimeToString(new Date(cellValue), columnScope.Type);
                                }
                                else if(cellValue.constructor == Date){
                                    cellText = BaseFunction.dateTimeToString(cellValue, columnScope.Type);
                                }
                                else{
                                    cellText = "&nbsp";
                                }
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.Refer){
                                try{
                                    cellText = eval("cellValue." + columnScope.TextField);
                                }
                                catch(e){
                                    cellText = "&nbsp";
                                }
                            }
                            else if(columnScope.ControllType == BaseEnum.ControllType.DropDownList){
                                cellText = "&nbsp";
                                for(var option in columnScope.enum){
                                    if(columnScope.enum[option].Value == cellValue){
                                        cellText = columnScope.enum[option].Text;
                                        break;
                                    }
                                }
                            }
                            else{
                                cellText = "&nbsp";
                            }
                        }                        
                            
                        var rowIndex = $scope.getRowIndex(focusedRecord._id);
                        var cellIndex = $scope.getCellIndex(columnScope.ValueField);
                        $scope.setCellText(rowIndex, cellIndex, cellText);

                        if(oldValue != cellValue){
                            $scope.cellValueChange(columnScope.ValueField, cellValue, oldValue);
                        }                        
                    });
                }
            };
            $scope.cellValueChange = function(columnName, newValue, oldValue){
                $scope.EventManage.dispatchEvent("onChange_" + columnName);
                $scope.cellvaluechange({
                    columnName: columnName,
                    newValue: newValue,
                    oldValue: oldValue
                });
                $scope.$digest();
            };
            $scope.addRowHtml = function(record, rowIndex){
                //创建checkbox列
                if($scope.IsSelect){
                    var newBodyLeftRow;
                    if(rowIndex != undefined && rowIndex >=0){
                        newBodyLeftRow = $scope.Dom._BodyLeftElement.insertRow(rowIndex);
                    }
                    else{
                        newBodyLeftRow = $scope.Dom._BodyLeftElement.insertRow();
                    }

                    if($scope.module.FocusedRecord != null && record._id == $scope.module.FocusedRecord._id){
                        newBodyLeftRow.style.backgroundColor = '#FAEBB2';
                    }
                    newBodyLeftRow.setAttribute('key', record._id);
                    newBodyLeftRow.addEventListener('click', function(){ $scope.$apply($scope.rowClick()); }, true);
                    newBodyLeftRow.addEventListener('dblclick', function(){ $scope.$apply($scope.rowdblclick()); }, false);
                    var newBodyLeftRowCell = newBodyLeftRow.insertCell();

                    newBodyLeftRowCell.innerHTML +=
                        '<div style="width:' + $scope.CheckColumn.Width + ';">' + 
                            '<input type="checkbox" class="CheckBox" ' + (record.IsSelected ? 'checked="true"' : '')  + ' "/>' + 
                        '</div>';

                    newBodyLeftRowCell.children[0].children[0].addEventListener('click', function(){ $scope.$apply($scope.checkedLineClick()); }, false);
                    newBodyLeftRowCell.children[0].children[0].addEventListener('keydown', function(){
                        if(event.keyCode == 32) {
                            event.srcElement.checked = !event.srcElement.checked;
                            $scope.$apply($scope.checkedLineClick());
                            event.preventDefault();
                        }
                    }, false);
                }

                //创建表体区域
                var newBodyRow;
                if(rowIndex != undefined && rowIndex >=0){
                    newBodyRow = $scope.Dom._BodyElement.insertRow(rowIndex);
                }
                else{
                    newBodyRow = $scope.Dom._BodyElement.insertRow();
                }

                if(this.FocusedRecord != null && record._id == this.FocusedRecord._id){
                    newBodyRow.style.backgroundColor = '#FAEBB2';
                }
                newBodyRow.setAttribute('key', record._id);
                newBodyRow.addEventListener('click', function(){ $scope.$apply($scope.rowClick()); }, true);
                newBodyRow.addEventListener('dblclick', function(){ $scope.$apply($scope.rowdblclick()); }, false);
                for (var i = 0; i < $scope.Columns.length; i++){
                    var column = $scope.Columns[i];
                    var newBodyRowCell = newBodyRow.insertCell();

                    if(!column.scope.IsDisplay){
                        newBodyRowCell.style.display = 'none';
                    }

                    if(column.scope.ControllType != BaseEnum.ControllType.Html) {
                        var cellValue;
                        if(column.scope.ValueField.indexOf(".") >= 0){
                            var fields = column.scope.ValueField.split(".");
                            var strEvalField = "record";
                            for(var j=0; j<fields.length; j++){
                                strEvalField += "." + fields[j];
                                cellValue = eval(strEvalField);
                                if(j < fields.length - 1){
                                    if(cellValue == undefined || cellValue == null || cellValue.constructor != Object){
                                        eval(strEvalField + " = {}");
                                    }
                                }
                            }
                        }
                        else{
                            cellValue = record[column.scope.ValueField];
                        }
                        if(column.scope.ControllType == BaseEnum.ControllType.TextBox){
                            if(cellValue == undefined || cellValue == null || cellValue == ''){
                                cellValue = '&nbsp;';
                            }
                        }
                        else if(column.scope.ControllType == BaseEnum.ControllType.NumberBox){
                            var round = column.scope.getRound(record);
                            if(round != null) {
                                cellValue = round.formatNumber(cellValue);
                            }
                            else{
                                if(cellValue == undefined || cellValue == null){
                                    cellValue = '';
                                }
                            }
                        }
                        else if(column.scope.ControllType == BaseEnum.ControllType.PercentBox){
                            var round = column.scope.getRound(record);
                            if(round != null) {
                                cellValue = round.formatPercent(cellValue);
                            }
                            else{
                                cellValue = (cellValue * 100).toString() + "%";
                            }
                        }
                        else if(column.scope.ControllType == BaseEnum.ControllType.CheckBox){
                            if(cellValue){
                                cellValue = '<div class="Hook"/>'; //'&radic;';
                            }
                            else{
                                cellValue = '&nbsp;';
                            }
                        }
                        else if(column.scope.ControllType == BaseEnum.ControllType.Calendar){
                            if(cellValue == undefined || cellValue == null || cellValue.constructor == undefined){
                                cellValue = '&nbsp;';
                            }
                            else if(cellValue.constructor == String){
                                if(cellValue.trim() == ""){
                                    cellValue = '&nbsp;';
                                }
                                else{
                                    cellValue = (BaseFunction.dateTimeToString(new Date(cellValue), column.scope.Format));
                                }
                            }
                            else if(cellValue.constructor == Date){
                                cellValue = (BaseFunction.dateTimeToString(new Date(cellValue), column.scope.Format));
                            }
                        }
                        else if(column.scope.ControllType == BaseEnum.ControllType.Refer){
                            if(record[column.scope.ValueField] && record[column.scope.ValueField][column.scope.TextField]){
                                cellValue = record[column.scope.ValueField][column.scope.TextField].trim();
                            }
                            else{
                                cellValue = "&nbsp;";
                            }
                        }
                        else if(column.scope.ControllType == BaseEnum.ControllType.DropDownList) {
                            if(cellValue != undefined && cellValue !== "" && cellValue > -1) {
                                var isFind = false;
                                for(var option in column.scope.enum){
                                    if(column.scope.enum[option].Value == cellValue){
                                        isFind = true;
                                        cellValue = column.scope.enum[option].Text;
                                        break;
                                    }                                
                                }
                                if(!isFind){
                                    cellValue = '&nbsp;';
                                }
                            }
                            else{
                                cellValue = '&nbsp;';
                            }
                        }

                        if(cellValue != "&nbsp;" && column.scope.ControllType != BaseEnum.ControllType.CheckBox){
                            newBodyRowCell.innerHTML = '<div title="' + cellValue + '">' + cellValue + '</div>';
                        }
                        else{
                            newBodyRowCell.innerHTML = '<div>' + cellValue + '</div>';
                        }
                        newBodyRowCell.children[0].setAttribute('class', column.scope.TextAlignClass);
                        newBodyRowCell.children[0].style.width = (Number(column.scope.Width.replace('px', '')) - 4).toString() + 'px';

                        newBodyRowCell.children[0].addEventListener('click', function () {
                            $scope.cellClick();
                        }, false);
                    }
                    else{
                        var columnHtml = '<div>' + column.Element.innerHTML + '</div>';
                        var reg = new RegExp("CurrentRecord","gi");     //更新全部，不区分大小写
                        columnHtml = columnHtml.replace(reg, 'module.findRecordById(\'' + record._id + '\')');
                        reg = new RegExp('ng-click="',"gi");
                        columnHtml = columnHtml.replace(reg, 'ng-click="$parent.');

                        $compile(columnHtml)($scope, function (clone, $scope) {
                            newBodyRowCell.appendChild(clone[0]);
                            newBodyRowCell.children[0].style.width = (Number(column.scope.Width.replace('px', '')) - 4).toString() + 'px';
                        });
                    }
                }

                //创建操作栏区域
                if($scope.Edit.IsEdit && ($scope.Edit.IsAdd || $scope.Edit.IsDelete)){
                    var newBodyRightRow;
                    if(rowIndex != undefined && rowIndex >=0){
                        newBodyRightRow = $scope.Dom._BodyRightElement.insertRow(rowIndex);
                    }
                    else{
                        newBodyRightRow = $scope.Dom._BodyRightElement.insertRow();
                    }

                    if(this.FocusedRecord != null && record._id == this.FocusedRecord._id){
                        newBodyRightRow.style.backgroundColor = '#FAEBB2';
                    }
                    newBodyRightRow.setAttribute('key', record._id);
                    newBodyRightRow.addEventListener('click', function(){ $scope.$apply($scope.rowClick()); }, true);
                    newBodyRightRow.addEventListener('dblclick', function(){ $scope.$apply($scope.rowdblclick()); }, false);
                    var newBodyRightRowCell = newBodyRightRow.insertCell();

                    if($scope.Edit.IsAdd){
                        newBodyRightRowCell.innerHTML += '<img src="modules/Base/client/Images/addRow.png"/>';
                    }

                    if($scope.Edit.IsDelete){
                        if($scope.Edit.IsAdd){
                            newBodyRightRowCell.innerHTML += '<i>&nbsp;</i>';
                        }
                        newBodyRightRowCell.innerHTML += '<img src="modules/Base/client/Images/deleteRow.png"/>';
                    }

                    if($scope.Edit.IsAdd) {
                        newBodyRightRowCell.children[0].addEventListener('click', function () {
                            $scope.$apply($scope.addRow());
                        }, false);

                        if($scope.Edit.IsDelete){
                            newBodyRightRowCell.children[2].addEventListener('click', function () {
                                $scope.$apply($scope.deleteRow());
                            }, false);
                        }
                    }
                    else if($scope.Edit.IsDelete){
                        newBodyRightRowCell.children[0].addEventListener('click', function () {
                            $scope.$apply($scope.deleteRow());
                        }, false);
                    }
                }
            };
            $scope.addRowsHtml = function(records){
                if(records != undefined && records.constructor == Array){
                    for(var i=0; i<records.length; i++){
                        $scope.addRowHtml(records[i]);
                    }
                }
            };
            $scope.deleteRowHtml = function(rowIndex){
                if(rowIndex == undefined || rowIndex >= $scope.Dom._BodyElement.rows.length){
                    rowIndex = $scope.Dom._BodyElement.rows.length - 1;
                }

                if($scope.IsSelect) {
                    $scope.Dom._BodyLeftElement.deleteRow(rowIndex);
                }
                $scope.Dom._BodyElement.deleteRow(rowIndex);
                if($scope.Edit.IsEdit && ($scope.Edit.IsAdd || $scope.Edit.IsDelete)) {
                    $scope.Dom._BodyRightElement.deleteRow(rowIndex);
                }
            };
            $scope.deleteAllRowHtml = function(){
                while ($scope.Dom._BodyElement.rows.length > 0) {
                    $scope.deleteRowHtml();
                }
                $scope.Checked.IsCheckedAll = false;
            };

            //表格数据发生变化，需要全部重新显示
            $scope.refresh = function(records){
                $scope.deleteAllRowHtml();

                $scope.addRowsHtml(records);
                if ($scope.module.FocusedRecord != null) {
                    var focusedRow = $scope.getRowIndex($scope.module.FocusedRecord._id);
                    if (focusedRow >= 0) {
                        if($scope.IsSelect) {
                            $scope.Dom._BodyLeftElement.rows[focusedRow].style.backgroundColor = '#FAEBB2';
                        }
                        $scope.Dom._BodyElement.rows[focusedRow].style.backgroundColor = '#FAEBB2';
                        if($scope.Edit.IsEdit && ($scope.Edit.IsAdd || $scope.Edit.IsDelete)) {
                            $scope.Dom._BodyRightElement.rows[focusedRow].style.backgroundColor = '#FAEBB2';
                        }
                    }
                }
            };
            //行数据发生改变，需要刷新Grid显示
            $scope.refreshRows = function(records){
                for(var j=0; j<records.length; j++){
                    var record = records[j];
                    var rowIndex = $scope.getRowIndex(record._id);
                    if(rowIndex != -1){
                        for (var i = 0; i < $scope.Columns.length; i++){
                            var column = $scope.Columns[i];
                            if(column.scope.ControllType != BaseEnum.ControllType.Html) {
                                var cellValue;
                                if(column.scope.ValueField.indexOf(".") >= 0){
                                    var fields = column.scope.ValueField.split(".");
                                    var strEvalField = "record";
                                    for(var n=0; n<fields.length; n++){
                                        strEvalField += "." + fields[n];
                                        cellValue = eval(strEvalField);
                                        if(n < fields.length - 1){
                                            if(cellValue == undefined || cellValue == null || cellValue.constructor != Object){
                                                cellValue = undefined;
                                                break;
                                            }
                                        }
                                    }
                                }
                                else{
                                    cellValue = record[column.scope.ValueField];
                                }

                                if(column.scope.ControllType == BaseEnum.ControllType.TextBox){
                                    if(cellValue == undefined || cellValue == null || cellValue == ''){
                                        cellValue = '&nbsp;';
                                    }
                                }
                                else if(column.scope.ControllType == BaseEnum.ControllType.NumberBox){
                                    var round = column.scope.getRound(record);
                                    if(round != null) {
                                        cellValue = round.formatNumber(cellValue);
                                    }
                                    else{
                                        if(cellValue == undefined || cellValue == null){
                                            cellValue = '';
                                        }
                                    }
                                }
                                else if(column.scope.ControllType == BaseEnum.ControllType.PercentBox){
                                    var round = column.scope.getRound(record);
                                    if(round != null) {
                                        cellValue = round.formatPercent(cellValue);
                                    }
                                    else{
                                        cellValue = (cellValue * 100).toString() + "%";
                                    }
                                }
                                else if(column.scope.ControllType == BaseEnum.ControllType.CheckBox){
                                    if(cellValue){
                                        cellValue = '<div class="Hook"/>'; //'&radic;';
                                    }
                                    else{
                                        cellValue = '&nbsp;';
                                    }
                                }
                                else if(column.scope.ControllType == BaseEnum.ControllType.Calendar){
                                    if(cellValue == undefined || cellValue.constructor == undefined){
                                        cellValue = '&nbsp;';
                                    }
                                    else if(cellValue.constructor == String){
                                        cellValue = BaseFunction.dateTimeToString(new Date(cellValue), column.scope.Format);
                                    }
                                    else if(cellValue.constructor == Date){
                                        cellValue = BaseFunction.dateTimeToString(cellValue, column.scope.Format);
                                    }
                                }
                                else if(column.scope.ControllType == BaseEnum.ControllType.Refer){
                                    if(record[column.scope.ValueField] != null && record[column.scope.ValueField] != undefined){
                                        cellValue = record[column.scope.ValueField][column.scope.TextField].trim();
                                    }
                                    else{
                                        cellValue = "&nbsp;";
                                    }
                                }
                                else if(column.scope.ControllType == BaseEnum.ControllType.DropDownList) {
                                    if(cellValue != undefined && cellValue != null && cellValue > -1) {
                                        var isFind = false;
                                        for(var option in column.scope.enum){
                                            if(column.scope.enum[option].Value == cellValue){
                                                isFind = true;
                                                cellValue = column.scope.enum[option].Text;
                                                break;
                                            }                                
                                        }
                                        if(!isFind){
                                            cellValue = '&nbsp;';
                                        }
                                    }
                                    else{
                                        cellValue = '&nbsp;';
                                    }
                                }

                                $scope.Dom._BodyElement.rows[rowIndex].cells[i].children[0].innerHTML = cellValue;
                                if(cellValue != '&nbsp;' && column.scope.ControllType != BaseEnum.ControllType.CheckBox){
                                    $scope.Dom._BodyElement.rows[rowIndex].cells[i].children[0].setAttribute("title", cellValue);
                                }
                            }
                        }
                    }
                }
            };
            //行删除，需要同步删除Grid的行
            $scope.refreshDeleteRows = function(records){
                for(var j=0; j<records.length; j++){
                    if(records[j] == $scope.module.FocusedRecord){
                        $scope.module.FocusedRecord = null;
                    }
                    var rowIndex = $scope.getRowIndex(records[j]._id);
                    if(rowIndex != null && rowIndex > -1){
                        $scope.deleteRowHtml(rowIndex);
                    }
                }
            };

            $scope.DataGrid_OrderBy = null;
            $scope.__defineGetter__('OrderBy', function(){
                var orderBy = {};
                if($scope.DataGrid_OrderBy == null){
                    orderBy = $scope.module.OrderBy;
                }
                else{
                    if($scope.module.OrderBy == null){
                        orderBy = $scope.DataGrid_OrderBy;
                    }
                    else{                        
                        Object.assign(orderBy, $scope.module.OrderBy);
                        Object.assign(orderBy, $scope.DataGrid_OrderBy);  //DataGrid定义的排序将覆盖module的排序，不影响$scope.module.OrderBy值
                    }
                }

                if($scope.module.IsEntityModule && $scope.module.LoadMode != BaseEnum.LoadMode.CacheAndNoPaging){
                    var newOrderBy = {};
                    for(var key in orderBy){
                        if(orderBy[key] != null){
                            if(key.indexOf(".") >= 0){
                                newOrderBy[key.split(".")[0]] = orderBy[key];
                            }
                            else{
                                newOrderBy[key] = orderBy[key];
                            }
                        }
                    }
                    return newOrderBy;
                }
                else{
                    return orderBy;
                }
            });

            $scope.loadByOrder = function(){
                if($scope.IsOrder){
                    if($scope.module.IsEntityModule && $scope.module.LoadMode != BaseEnum.LoadMode.CacheAndNoPaging){
                        $scope.module.load($scope.Condition, $scope.OrderBy, function(records){
                            if($scope.order){
                                $scope.order(records);
                            }
                        });
                    }
                    else{
                        $scope.module.sort($scope.OrderBy);
                        $scope.deleteAllRowHtml();
                        if($scope.PageCount > 0){
                            $scope.assignPage(0);
                        }
                        if($scope.order){
                            $scope.order($scope.module.Records);
                        }
                    }
                }
            }
            $scope.setOrderBy = function(field, value){
                if($scope.IsOrder){
                    if($scope.DataGrid_OrderBy == null){
                        $scope.DataGrid_OrderBy = {};
                    }

                    if(value == BaseEnum.SortType.Empty.Value){
                        delete $scope.DataGrid_OrderBy[field];
                    }
                    else if(value == BaseEnum.SortType.Asc.Value){
                        $scope.DataGrid_OrderBy[field] = 1;
                    }
                    else if(value == BaseEnum.SortType.Desc.Value){
                        $scope.DataGrid_OrderBy[field] = -1;
                    }
                    $scope.GridConfig.OrderBy = $scope.DataGrid_OrderBy;
                }
            };

            $scope.DataGrid_Condition = null;
            $scope.__defineGetter__('Condition', function(){
                if($scope.DataGrid_Condition == null){
                    return $scope.module.Condition;
                }
                else{
                    if($scope.module.Condition == null){
                        return $scope.DataGrid_Condition;
                    }
                    else{
                        var condition = {$and: [$scope.module.Condition, $scope.DataGrid_Condition]};
                        return condition;
                    }
                }                
            });

            $scope.DataGrid_FilterID = "";  //查询窗口ID
            $scope.filterClick = function(){
                if($scope.DataGrid_FilterID == ""){
                    $scope.DataGrid_FilterID = BaseFunction.getGuid();
                    var filterContentElement = $scope.Dom._tableDiv.parentElement.children[1].children[0].children[0].children[0].children[1].children[0].children[0].children[1];
                    
                    var ownFilters = null;  //个性化条件集合
                    if($scope.GridConfig && $scope.GridConfig.Filters){
                        ownFilters = $scope.GridConfig.Filters;
                    }
                    $scope.filterCollection = [];
                    var filterContentHtml = '<div style="width:100%;min-height:200px;max-height:450px;overflow:auto;">';
                    for(var i=0; i<$scope.Columns.length; i++){
                        if($scope.Columns[i].scope.IsFilter && $scope.Columns[i].scope.ControllType.Value != BaseEnum.ControllType.Html.Value){
                            filterContentHtml += '<div class="row RowSpace">' + 
                                '<div class="LableDiv" style="width:120px;"><Label>' + $scope.Columns[i].scope.DisplayName + '</Label></div>' + 
                                '<div class="InputDiv" style="width:102px;">' + 
                                    '<DropDownList IsEmpty="false" change="filterCollection[' + i.toString() + '].ChangeEvent()" value="filterCollection[' + i.toString() + '].CompareRelationValue" Enum="filterCollection[' + i.toString() + '].CompareRelationEnum"></DropDownList>' + 
                                '</div>' + 
                                '<div class="InputDiv" style="width:280px;">';

                            var filterOption = {
                                ValueField: $scope.Columns[i].scope.ValueField,
                                ControllTypeValue: $scope.Columns[i].scope.ControllType.Value,
                                CompareRelationEnum: null,
                                CompareRelationValue: BaseEnum.CompareRelation.No.Value,
                                Value: null,
                                Value2: null,
                                Enabled: false,
                                IsDisplayController2: false,
                                ChangeEvent: function(){
                                    var self = this;
                                    $scope.$apply(function(){
                                        if(self.CompareRelationValue == BaseEnum.CompareRelation.No.Value || 
                                            self.CompareRelationValue == BaseEnum.CompareRelation.Empty.Value || 
                                            self.CompareRelationValue == BaseEnum.CompareRelation.NoEmpty.Value){
                                            self.Enabled = false;
                                            self.Value = null;
                                            self.Value2 = null;
                                        }
                                        else{
                                            self.Enabled = true;
                                            if(self.CompareRelationValue == BaseEnum.CompareRelation.Between.Value){
                                                self.IsDisplayController2 = true;
                                            }
                                            else{
                                                self.IsDisplayController2 = false;
                                            }
                                        }
                                    });
                                }
                            };

                            if(filterOption.ControllTypeValue == BaseEnum.ControllType.TextBox.Value) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Like: {Value: 1, Text: '包含'},
                                    NotLike: {Value: 2, Text: '不包含'},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    Empty: {Value: 12, Text: '空'},
                                    NoEmpty: {Value: 13, Text: '非空'}
                                };

                                filterContentHtml += '<TextBox value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></TextBox>';
                            }
                            else if(filterOption.ControllTypeValue == BaseEnum.ControllType.NumberBox.Value) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    GreatThen: {Value: 5, Text: '大于'},
                                    LessThan: {Value: 6, Text: '小于'},
                                    GreatThenEqual: {Value: 7, Text: '大于等于'},
                                    LessThanEqual: {Value: 8, Text: '小于等于'},
                                    Between: {Value: 11, Text: '两者之间'},
                                    Empty: {Value: 12, Text: '空'},
                                    NoEmpty: {Value: 13, Text: '非空'}
                                };

                                filterContentHtml += '<NumberBox value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></NumberBox>';
                                filterContentHtml += '<NumberBox visible="{{filterCollection[' + i.toString() + '].IsDisplayController2.toString()}}" style="margin-top:5px;" value="filterCollection[' + i.toString() + '].Value2" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></NumberBox>';
                            }
                            else if(filterOption.ControllTypeValue == BaseEnum.ControllType.PercentBox.Value) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    GreatThen: {Value: 5, Text: '大于'},
                                    LessThan: {Value: 6, Text: '小于'},
                                    GreatThenEqual: {Value: 7, Text: '大于等于'},
                                    LessThanEqual: {Value: 8, Text: '小于等于'},
                                    Between: {Value: 11, Text: '两者之间'},
                                    Empty: {Value: 12, Text: '空'},
                                    NoEmpty: {Value: 13, Text: '非空'}
                                };

                                filterContentHtml += '<PercentBox value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></PercentBox>';
                                filterContentHtml += '<PercentBox style="margin-top:5px;" visible="{{filterCollection[' + i.toString() + '].IsDisplayController2}}" value="filterCollection[' + i.toString() + '].Value2" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></PercentBox>';
                            }
                            else if(filterOption.ControllTypeValue == BaseEnum.ControllType.CheckBox.Value) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'}
                                };
                                filterContentHtml += '<CheckBox value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></CheckBox>';
                            }
                            else if(filterOption.ControllTypeValue == BaseEnum.ControllType.DropDownList.Value) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    Empty: {Value: 12, Text: '空'},
                                    NoEmpty: {Value: 13, Text: '非空'}
                                };
                                filterContentHtml += '<DropDownList enum="Columns[' + i.toString() + '].scope.enum" value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></DropDownList>';
                            }
                            else if(filterOption.ControllTypeValue == BaseEnum.ControllType.Refer.Value) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    Empty: {Value: 12, Text: '空'},
                                    NoEmpty: {Value: 13, Text: '非空'}
                                };

                                filterContentHtml += '<Refer IsInclude="true" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}" Condition="' + $scope.Columns[i].scope.Condition + '" ' + 
                                    'OrderBy="' + $scope.Columns[i].scope.OrderBy + '" ' + 
                                    'Populate="' + $scope.Columns[i].scope.Populate + '" ' +
                                    'value="filterCollection[' + i.toString() + '].Value" ' + 
                                    'keyfield="' + $scope.Columns[i].scope.KeyField + '" codefield="' + $scope.Columns[i].scope.CodeField + '" textfield="' + $scope.Columns[i].scope.TextField + '" ' + 
                                    'EntityName="' + $scope.Columns[i].scope.EntityName + '" windowtitle="' + $scope.Columns[i].scope.WindowTitle + '">';                                    

                                for(var j=0; j<$scope.Columns[i].scope.Columns.length; j++){
                                    var columnHtml = '<RColumn'
                                    if ($scope.Columns[i].scope.Columns[j].Type != undefined && $scope.Columns[i].scope.Columns[j].Type != "") {
                                        columnHtml += ' type="' + $scope.Columns[i].scope.Columns[j].Type + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].DisplayName != undefined && $scope.Columns[i].scope.Columns[j].DisplayName != "") {
                                        columnHtml += ' displayname="' + $scope.Columns[i].scope.Columns[j].DisplayName + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].Width != undefined && $scope.Columns[i].scope.Columns[j].Width != "") {
                                        columnHtml += ' width="' + $scope.Columns[i].scope.Columns[j].Width + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].ValueField != undefined && $scope.Columns[i].scope.Columns[j].ValueField != "") {
                                        columnHtml += ' valuefield="' + $scope.Columns[i].scope.Columns[j].ValueField + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].Enum != undefined && $scope.Columns[i].scope.Columns[j].Enum != "") {
                                        columnHtml += ' enum="' + $scope.Columns[i].scope.Columns[j].Enum + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].Round != undefined && $scope.Columns[i].scope.Columns[j].Round != "") {
                                        columnHtml += ' round="' + $scope.Columns[i].scope.Columns[j].Round + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].CalendarType != undefined && $scope.Columns[i].scope.Columns[j].CalendarType != "") {
                                        columnHtml += ' calendartype="' + $scope.Columns[i].scope.Columns[j].CalendarType + '"';
                                    }
                                    columnHtml += '></RColumn>';
                                    filterContentHtml += columnHtml;
                                }
                                filterContentHtml += '</Refer>';
                            }
                            else if(filterOption.ControllTypeValue == BaseEnum.ControllType.Calendar.Value) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    GreatThen: {Value: 5, Text: '大于'},
                                    LessThan: {Value: 6, Text: '小于'},
                                    GreatThenEqual: {Value: 7, Text: '大于等于'},
                                    LessThanEqual: {Value: 8, Text: '小于等于'},
                                    Between: {Value: 11, Text: '两者之间'}
                                };
                                if($scope.Columns[i].scope.Format == BaseEnum.DateTimeFormat.Date){
                                    filterContentHtml += '<Calendar Format="Date" value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></Calendar>';
                                    filterContentHtml += '<Calendar style="margin-top:5px;" Format="Date" visible="{{filterCollection[' + i.toString() + '].IsDisplayController2}}" value="filterCollection[' + i.toString() + '].Value2" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></Calendar>';
                                }
                                else{
                                    filterContentHtml += '<Calendar Format="DateTime" value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></Calendar>';
                                    filterContentHtml += '<Calendar Format="DateTime" style="margin-top:5px;" visible="{{filterCollection[' + i.toString() + '].IsDisplayController2}}" value="filterCollection[' + i.toString() + '].Value2" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></Calendar>';
                                }
                            }

                            //个性化处理
                            if(ownFilters && ownFilters.hasOwnProperty(filterOption.ValueField)){
                                filterOption.CompareRelationValue = ownFilters[filterOption.ValueField].CompareRelationValue;
                                
                                if(filterOption.CompareRelationValue != BaseEnum.CompareRelation.No.Value && 
                                    filterOption.CompareRelationValue != BaseEnum.CompareRelation.Empty.Value && 
                                    filterOption.CompareRelationValue != BaseEnum.CompareRelation.NoEmpty.Value){
                                    filterOption.Value = ownFilters[filterOption.ValueField].Value;
                                    filterOption.Enabled = true;
                                    if(filterOption.CompareRelationValue == BaseEnum.CompareRelation.Between.Value){
                                        filterOption.Value2 = ownFilters[filterOption.ValueField].Value2;
                                        filterOption.IsDisplayController2 = true;
                                    }
                                }
                            }

                            $scope.filterCollection.push(filterOption);
                            filterContentHtml += '</div></div>';
                        }
                    }
                    filterContentHtml += '</div>';

                    $compile(filterContentHtml)($scope, function (clone, $scope) {
                        filterContentElement.appendChild(clone[0]);
                    });
                }
            };
            $scope.btnFilterOKClick = function(){
                var ownFilters = {};
                for(var i=0; i<$scope.filterCollection.length; i++){
                    if($scope.filterCollection[i].CompareRelationValue != BaseEnum.CompareRelation.No.Value){
                        //校验
                        if($scope.filterCollection[i].CompareRelationValue != BaseEnum.CompareRelation.Empty.Value
                            && $scope.filterCollection[i].CompareRelationValue != BaseEnum.CompareRelation.NoEmpty.Value){
                            if($scope.filterCollection[i].Value == null || $scope.filterCollection[i].Value == undefined){
                                BaseFunction.alert($scope.filterCollection[i].Column.DisplayName + "条件值不能为空", "查询条件错误");
                                return;
                            }
                            else if($scope.filterCollection[i].CompareRelationValue == BaseEnum.CompareRelation.Between.Value
                                && ($scope.filterCollection[i].Value2 == null || $scope.filterCollection[i].Value2 == undefined)){
                                BaseFunction.alert($scope.filterCollection[i].Column.DisplayName + "条件为两者之间，两个值都不能为空", "查询条件错误");
                                return;
                            }
                        }

                        ownFilters[$scope.filterCollection[i].ValueField] = {
                            ValueField: $scope.filterCollection[i].ValueField,
                            ControllTypeValue: $scope.filterCollection[i].ControllTypeValue,
                            CompareRelationValue: $scope.filterCollection[i].CompareRelationValue,
                            Value: $scope.filterCollection[i].Value,
                            Value2: $scope.filterCollection[i].Value2
                        };
                    }
                }

                var filtrations = BaseFunction.getFiltersCondition(ownFilters, $scope.module.IsEntityModule);
                $scope.GridConfig.Filters = ownFilters;

                if($scope.module.IsEntityModule){
                    $scope.DataGrid_Condition = filtrations;
                    $scope.module.load($scope.Condition, $scope.OrderBy);
                }
                else{
                    $scope.module.Filtration = filtrations;
                    $scope.RecordCount = $scope.module.Records.length;

                    if($scope.PageCount > 0){
                        $scope.firstPage();
                    }
                    else{
                        $scope.deleteAllRowHtml();
                        $scope.module.FocusedRecord = null;
                        $scope.turnpage({records: $scope.module.Records});
                        $scope.rowchange();
                    }
                }
                $('#' + $scope.DataGrid_FilterID).modal('hide');
            };
            $scope.btnFilterCancelClick = function(){
                $('#' + $scope.DataGrid_FilterID).modal('hide');
            };
            
            $scope.ExcelTempletValue = 0;
            $scope.ExcelTempletEnum = { Default: {Value: 0, Text: '默认'} };
            $scope.DataGrid_ExportExcelID = "";  //导出窗口ID
            $scope.exportExcelClick = function(){
                if($scope.DataGrid_ExportExcelID == ""){
                    $scope.DataGrid_ExportExcelID = BaseFunction.getGuid();
                }
            };
            $scope.btnExportExcelOKClick = function(){
                $('#' + $scope.DataGrid_ExportExcelID).modal('hide');
                if($scope.ExcelTempletValue == $scope.ExcelTempletEnum.Default.Value){
                    BaseExcel.exportDataGridExcel($scope);
                }
                $scope.GridConfig.ExportTemplateValue = $scope.ExcelTempletValue;
            };
            $scope.btnExportExcelCancelClick = function(){
                $('#' + $scope.DataGrid_ExportExcelID).modal('hide');
            };

            //翻页代码
            $scope.RecordCount = 0;
            $scope.PageNum = -1;
            $scope.PageRecords = null;
            $scope.DisplayPageCount = 5;     //显示的页数
            $scope.DisplayPages = [];

            $scope.__defineGetter__('PageCount', function(){
                return Math.ceil($scope.RecordCount / $scope.module.PageSize);
            });

            $scope.setDisplayPages = function(){
               $scope.DisplayPages = new Array();

              if($scope.PageCount <= $scope.DisplayPageCount){
                 for(var i=0; i<$scope.PageCount; i++){
                     $scope.DisplayPages.push(i);
                 }
              }
              else{
                 if($scope.PageNum + 1 <= Math.ceil($scope.DisplayPageCount / 2)){
                     for(var i=0; i<$scope.DisplayPageCount; i++) {
                         $scope.DisplayPages.push(i);
                     }
                 }
                 else if($scope.PageCount - ($scope.PageNum + 1) < Math.ceil($scope.DisplayPageCount / 2)){
                     for(var i=$scope.PageCount - $scope.DisplayPageCount; i<$scope.PageCount; i++){
                         $scope.DisplayPages.push(i);
                     }
                 }
                 else{
                     var firstPageNum = $scope.PageNum - Math.floor($scope.DisplayPageCount / 2);
                     for(var i=0; i<$scope.DisplayPageCount; i++){
                         $scope.DisplayPages.push(firstPageNum + i);
                     }
                 }
              }
            };

            var keyCodes = [13, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
            $scope.toolBar_KeyPress = function(){
                if(keyCodes.indexOf(event.keyCode) < 0){
                    event.returnValue = false;
                    return;
                }

                if(event.keyCode == 13) {
                    $scope.pageNumBoxChange();
                }
            };
            $scope.pageNumBoxChange = function(){
                if(event.srcElement.value.trim() != ''){
                    var pageNum = event.srcElement.value;
                    event.srcElement.value = "";

                    if($scope.PageCount > 0){
                        if(pageNum < 1){
                            pageNum = 1;
                        }
                        else if(pageNum > $scope.PageCount){
                            pageNum = $scope.PageCount;
                        }

                        if(pageNum > 0 && pageNum-1 != $scope.PageNum){
                            $scope.assignPage(pageNum-1);
                        }
                    }
                }
            };

            $scope.firstPage = function(completeFun){
                if($scope.PageCount > 0){
                    $scope.assignPage(0, completeFun);
                }
            };
            $scope.prePage = function(completeFun){
                if($scope.PageNum > 0 && $scope.PageCount > $scope.PageNum){
                    $scope.assignPage($scope.PageNum - 1, completeFun);
                }
            };
            $scope.nextPage = function(completeFun){
                if($scope.PageCount-1 > $scope.PageNum){
                    $scope.assignPage($scope.PageNum + 1, completeFun);
                }
            };
            $scope.lastPage = function(completeFun){
                if($scope.PageCount > 0){
                    $scope.assignPage($scope.PageCount - 1, completeFun);
                }
            };
            $scope.pageNumClick = function(pageNum, completeFun){
                $scope.assignPage(pageNum, completeFun);
            };
            $scope.assignPage = function(pageNum, completeFun){
                if(pageNum >= 0 && pageNum < $scope.PageCount){
                    if ($scope.module.LoadMode == BaseEnum.LoadMode.CacheAndNoPaging) {
                        $scope.PageNum = pageNum;
                        var pageRecords = $scope.module.Records.slice(pageNum * $scope.module.PageSize, (pageNum+1) * $scope.module.PageSize);
                        $scope.module.FocusedRecord = pageRecords[0];
                        $scope.refresh(pageRecords);

                        if(completeFun != undefined && completeFun != null) {
                            completeFun(pageRecords);
                        }

                        $scope.turnpage({records: pageRecords});
                        $scope.rowchange();
                    }
                    else if($scope.module.LoadMode == BaseEnum.LoadMode.CacheAndPaging){
                        if($scope.PageRecords[pageNum] != undefined){
                            $scope.PageNum = pageNum;
                            $scope.module.FocusedRecord = $scope.PageRecords[pageNum][0];
                            $scope.refresh($scope.PageRecords[pageNum]);

                            if(completeFun != undefined && completeFun != null) {
                                completeFun($scope.PageRecords[pageNum]);
                            }
                            $scope.turnpage({records: $scope.PageRecords[pageNum]});
                            $scope.rowchange();
                        }
                        else{
                            $scope.module.loadByPage($scope.Condition, $scope.OrderBy, pageNum, null, function(pageRecords){
                                $scope.PageNum = pageNum;
                                $scope.PageRecords[pageNum] = pageRecords;
                                $scope.module.FocusedRecord = pageRecords[0];
                                $scope.refresh(pageRecords);

                                if(completeFun != undefined && completeFun != null) {
                                    completeFun(pageRecords);
                                }
                                $scope.turnpage({records: pageRecords});
                                $scope.rowchange();
                            });
                        }
                    }
                    else if ($scope.module.LoadMode == BaseEnum.LoadMode.NoCacheAndPaging) {
                        $scope.module.Records = [];
                        $scope.module.loadByPage($scope.Condition, $scope.OrderBy, pageNum, null, function(pageRecords){
                            $scope.PageNum = pageNum;
                            $scope.module.Records = pageRecords;
                            $scope.module.FocusedRecord = pageRecords[0];
                            $scope.refresh(pageRecords);

                            if(completeFun != undefined && completeFun != null) {
                                completeFun(pageRecords);
                            };
                            $scope.turnpage({records: pageRecords});
                            $scope.rowchange();
                        });
                    }
                }
            };
        }],
        link: function (scope, element, attrs) {
            scope.ID = "";
            scope.Width = '100%';
            scope.Height = '100%';
            scope.IsSelect = false;    //是否支持选择
            scope.IsFilter = true;
            scope.IsAutoLoad = true;
            scope.IsOrder = true;
            scope.IsExport = true;      //是否支持默认导出
            scope.SheetName = '';     //导出页签名称
            scope.ExcelName = '';

            if (attrs["id"] != undefined && attrs["id"].trim() != "") {
                scope.ID = attrs["id"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
            }
            if (attrs["height"] != undefined && attrs["height"].trim() != "") {
                scope.Height = attrs["height"].trim();
            }
            if (attrs["isselect"] != undefined && attrs["isselect"].toLocaleLowerCase() == "true") {
                scope.IsSelect = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isautoload"] != undefined && attrs["isautoload"].toLocaleLowerCase() == "false") {
                scope.IsAutoLoad = false;
            }

            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }
            if (attrs["isexport"] != undefined && attrs["isexport"].toLocaleLowerCase() == "false") {
                scope.IsExport = false;                
            }
            else{
                if (attrs["excelname"] != undefined && attrs["excelname"].trim() != "") {
                    scope.ExcelName = attrs["excelname"].trim();
                }
                if (attrs["sheetname"] != undefined && attrs["sheetname"].trim() != "") {
                    scope.SheetName = attrs["sheetname"].trim();
                }
            }

            //防止设置错误，这里默认处理
            if(scope.Edit.IsEdit || !scope.module.IsEntityModule){
                scope.module.LoadMode = BaseEnum.LoadMode.CacheAndNoPaging;
            }
            else{
                scope.module.LoadMode = BaseEnum.LoadMode.CacheAndPaging;
            }
            
            //以下是表格的拖动处理代码
            var tableBody = element[0].children[0];
            var tableFooter = element[0].children[1];

            scope.Dom = {
                _tableDiv: tableBody,
                _addRowDiv: tableBody.children[1],
                _HeadLeftElement: tableBody.children[0].rows[0].cells[0].children[0],
                _HeadElement: tableBody.children[0].rows[0].cells[1].children[0],
                _HeadRightElement: tableBody.children[0].rows[0].cells[2].children[0],
                _BodyLeftElement: tableBody.children[0].rows[1].cells[0].children[0],
                _BodyElement: tableBody.children[0].rows[1].cells[1].children[0],
                _BodyRightElement: tableBody.children[0].rows[1].cells[2].children[0],

                _IsHeadMouseDown: false,
                _HeadMouseDownTD: null,
                _HeadMouseDownX: 0,
                _MouseMoveLine: null,
                _HeadChangeWidthTD: null
            };            

            //个性化
            var GridConfig = function(pageConfigName, gridConfigName, columnsHtml){
                this.PageConfigName = pageConfigName;
                this.GridConfigName = gridConfigName;

                this._PageConfig = JSON.parse(BaseFunction.LocalStorage.getItem(pageConfigName));
                this._GridConfig = null;

                if(!this._PageConfig){
                    this._PageConfig = {};
                }

                if(this._PageConfig[this.GridConfigName]){
                    this._GridConfig = this._PageConfig[this.GridConfigName];
                    if(this._GridConfig.ColumnsHtml != columnsHtml){
                        this._GridConfig.ColumnsHtml = columnsHtml;
                        this._GridConfig.Columns = null;     //columnsHtml.match(/\s*<\s*column\s*.*?((\s*\/\s*>\s*)|(\s*<\s*\/\s*column\s*>\s*))/gi);
                        this._GridConfig.Filters = null;
                        this._GridConfig.OrderBy = null;
                    }
                }
                else{
                    this._GridConfig = {
                        ColumnsHtml: columnsHtml,           //标准列Html
                        Columns: null,                      //列Html
                        Filters: null,                      //过滤条件集合
                        OrderBy: null,                      //排序条件
                        ExportTemplateValue: scope.ExcelTempletEnum.Default.Value           //默认打印模板
                    }
                }
            };
            GridConfig.prototype = {
                get ColumnsHtml(){
                    return this._GridConfig.ColumnsHtml;
                },
                set ColumnsHtml(val){
                    this._GridConfig['ColumnsHtml'] = val;
                },
                get Columns(){
                    if(this._GridConfig.Columns){
                        return this._GridConfig.Columns;
                    }
                    else{
                        return this._GridConfig.ColumnsHtml.match(/\s*<\s*column\s*.*?((\s*\/\s*>\s*)|(\s*<\s*\/\s*column\s*>\s*))/gi);
                    }
                },
                get Filters(){
                    return this._GridConfig.Filters;
                },
                set Filters(val){
                    this._GridConfig['Filters'] = val;
                    this.save();
                },
                get OrderBy(){
                    return this._GridConfig.OrderBy;
                },
                set OrderBy(val){
                    this._GridConfig['OrderBy'] = val;
                    this.save();
                },
                get ExportTemplate(){
                    return this._GridConfig.ExportTemplate;
                },
                set ExportTemplate(val){
                    this._GridConfig['ExportTemplate'] = val;
                    this.save();
                },

                setColumn: function(index, val){
                    if(!this._GridConfig.Columns){
                        this._GridConfig.Columns = this.ColumnsHtml.match(/\s*<\s*column\s*.*?((\s*\/\s*>\s*)|(\s*<\s*\/\s*column\s*>\s*))/gi);
                    }
                    this._GridConfig.Columns[index] = val;
                    this.save();
                },
                moveColumn: function(index, newIndex){
                    if(!this._GridConfig.Columns){
                        this._GridConfig.Columns = this.ColumnsHtml.match(/\s*<\s*column\s*.*?((\s*\/\s*>\s*)|(\s*<\s*\/\s*column\s*>\s*))/gi);
                    }
                    this.Columns.splice(newIndex, 0, this.Columns.splice(index, 1)[0]);
                    this.save();
                },
                save: function(){
                    this._PageConfig[this.GridConfigName] = this._GridConfig;
                    BaseFunction.LocalStorage.setItem(this.PageConfigName, JSON.stringify(this._PageConfig));
                }
            };

            var pageConfigName = null;
            if(BaseConfig.User){
                pageConfigName = BaseConfig.User.Code + '|' + document.location.pathname;
            }
            else{
                pageConfigName = document.location.pathname;
            }
            var gridConfigName = "DataGrid_" + scope.module.EntityName;
            if(scope.ID.length > 0){
                gridConfigName += "_" + scope.ID;
            }
            var columnsHtml = scope.Dom._HeadElement.children[0].children[0].innerHTML.trim().replace(/(\n)|(\r)|(\t)|(\v)/g, '').replace(/>\s*</g, '><');
            scope.GridConfig = new GridConfig(pageConfigName, gridConfigName, columnsHtml);
            if(scope.GridConfig.Filters){
                var conditions = BaseFunction.getFiltersCondition(scope.GridConfig.Filters, scope.module.IsEntityModule);
                if(scope.module.IsEntityModule){
                    scope.DataGrid_Condition = conditions;
                }
                else{
                    scope.module.Filtration = conditions;
                }
            }
            if(scope.GridConfig.OrderBy){
                scope.DataGrid_OrderBy = scope.GridConfig.OrderBy;
            }
            if(scope.GridConfig.ExportTemplateValue){
                $scope.ExcelTempletValue = scope.GridConfig.ExportTemplateValue;
            }

            //创建列
            var headElementTr = scope.Dom._HeadElement.children[0].children[0];
            headElementTr.removeAttribute('ng-transclude');
            headElementTr.innerHTML = "";
            var columnsHtml = scope.GridConfig.Columns;
            columnsHtml.forEach((columnHtml, i) => headElementTr.innerHTML += columnHtml);

            var columnLength = headElementTr.children.length;
            for(var i=0; i<columnLength; i++){
                var columnDom = headElementTr.children[0];
                var columnType = columnDom.getAttribute('type');
                if(columnType == null || columnType.trim().toLowerCase() == 'textbox' || parseInt(columnType.trim()) == BaseEnum.ControllType.TextBox.Value){                    
                    columnType = 'TextBoxColumn';
                }
                else if(columnType.trim().toLowerCase() == 'checkbox' || parseInt(columnType.trim()) == BaseEnum.ControllType.CheckBox.Value){
                    columnType = 'CheckBoxColumn';
                    
                }
                else if(columnType.trim().toLowerCase() == 'numberbox' || parseInt(columnType.trim()) == BaseEnum.ControllType.NumberBox.Value){
                    columnType = 'NumberBoxColumn';
                    
                }
                else if(columnType.trim().toLowerCase() == 'percentbox' || parseInt(columnType.trim()) == BaseEnum.ControllType.PercentBox.Value){
                    columnType = 'PercentBoxColumn';
                    
                }
                else if(columnType.trim().toLowerCase() == 'dropdownlist' || parseInt(columnType.trim()) == BaseEnum.ControllType.DropDownList.Value){
                    columnType = 'DropDownListColumn';
                    
                }
                else if(columnType.trim().toLowerCase() == 'refer' || parseInt(columnType.trim()) == BaseEnum.ControllType.Refer.Value){
                    columnType = 'ReferColumn';
                    
                }
                else if(columnType.trim().toLowerCase() == 'calendar' || parseInt(columnType.trim()) == BaseEnum.ControllType.Calendar.Value){
                    columnType = 'CalendarColumn';
                    
                }
                else if(columnType.trim().toLowerCase() == 'html' || parseInt(columnType.trim()) == BaseEnum.ControllType.Html.Value){
                    columnType = 'HtmlColumn';
                }

                columnDom.removeAttribute('type');

                if(columnType != null){
                    var columnHtml = columnDom.outerHTML.replace(/<\s*Column/i, '<' + columnType)
                                                 .replace(/\s*<\s*\/\s*Column\s*>$/i, '</' + columnType + '>')
                                                 .replace(/\s*\/\s*>$/, '></' + columnType + '>');

                    columnHtml = columnHtml.replace(/\s*titleclick\s*=\s*"/i, ' titleclick="$parent.');
                    if(columnType == 'ReferColumn'){
                        columnHtml = columnHtml.replace(/\s*beforeshow\s*=\s*"/i, ' beforeshow="$parent.');
                    }
                    else if(columnType == 'DropDownListColumn'){
                        columnHtml = columnHtml.replace(/\s*Enum\s*=\s*"/i, ' Enum="$parent.');
                    }
                    $compile(columnHtml)(scope, function(clonedElement, scope) {
                        headElementTr.appendChild(clonedElement[0]);
                    });
                }
                headElementTr.removeChild(headElementTr.children[0]);            
            }

            scope._scroll = function () {
                scope.Dom._HeadLeftElement.style.top = event.srcElement.scrollTop + 'px';
                scope.Dom._HeadLeftElement.style.left = event.srcElement.scrollLeft + 'px';
                scope.Dom._HeadElement.style.top = event.srcElement.scrollTop + 'px';
                scope.Dom._BodyLeftElement.style.left = event.srcElement.scrollLeft + 'px';

                if (scope.Edit.IsEdit) {
                    scope.Dom._HeadRightElement.style.top = event.srcElement.scrollTop + 'px';
                }
            };
            scope._mouseDown = function () {
                if (event.srcElement.tagName != "TD") {
                    return;
                }

                scope.Dom._HeadMouseDownX = event.clientX;
                scope.Dom._HeadMouseDownTD = event.srcElement;
                scope.Dom._HeadChangeWidthTD = event.srcElement;

                if (scope.Dom._HeadMouseDownX < scope.Dom._HeadChangeWidthTD.getBoundingClientRect().right - 5) {
                    if (scope.Dom._HeadChangeWidthTD.cellIndex == 0) {
                        scope.Dom._HeadChangeWidthTD = scope.Dom._HeadLeftElement.rows[0].cells[0];
                        if(!scope.IsSelect){
                            return;
                        }
                    }
                    else {
                        scope.Dom._HeadChangeWidthTD = scope.Dom._HeadElement.rows[0].cells[scope.Dom._HeadChangeWidthTD.cellIndex - 1];
                    }
                }

                scope.Dom._IsHeadMouseDown = true;
                scope.Dom._HeadMouseDownTD.style.cursor = "col-resize";
                scope.Dom._MouseMoveLine = document.createElement("div");
                scope.Dom._MouseMoveLine.className = "DivLine";
                scope.Dom._MouseMoveLine.style.height = scope.Dom._tableDiv.clientHeight.toString() + 'px';
                scope.Dom._MouseMoveLine.style.left = event.clientX.toString() + 'px';
                scope.Dom._MouseMoveLine.style.top = (scope.Dom._tableDiv.getBoundingClientRect().top + document.body.scrollTop).toString() + 'px';
                document.body.appendChild(scope.Dom._MouseMoveLine);

                window.addEventListener('mousemove', scope._mouseMove, false);
                window.addEventListener('mouseup', scope._mouseUp, false);
            };
            scope._mouseUp = function () {
                if (scope.Dom._IsHeadMouseDown) {
                    scope.Dom._IsHeadMouseDown = false;

                    if (scope.Dom._HeadMouseDownTD != null) {
                        window.removeEventListener('mousemove', scope._mouseMove, false);
                        window.removeEventListener('mouseup', scope._mouseUp, false);
                        //_HeadMouseDownTD.releaseCapture();
                        //window.releaseEvents(Event.MOUSEMOVE|Event.MOUSEUP);
                    }

                    scope.Dom._HeadMouseDownTD.style.cursor = "e-resize";
                    scope.Dom._HeadMouseDownTD = null;

                    if (scope.Dom._HeadChangeWidthTD.offsetWidth + event.clientX - scope.Dom._HeadMouseDownX <= 10) {
                        if (scope.Dom._HeadChangeWidthTD == scope.Dom._HeadLeftElement.rows[0].cells[0]) {
                            scope.CheckColumn.Width = '10px';
                        }
                        else {
                            scope.Columns[scope.Dom._HeadChangeWidthTD.cellIndex].scope.Width = '10px';
                        }
                    }
                    else {
                        var widh = scope.Dom._HeadChangeWidthTD.offsetWidth + event.clientX - scope.Dom._HeadMouseDownX;
                        if (scope.Dom._HeadChangeWidthTD == scope.Dom._HeadLeftElement.rows[0].cells[0]) {
                            scope.CheckColumn.Width = (widh - 4).toString() + "px";
                        }
                        else {
                            scope.Columns[scope.Dom._HeadChangeWidthTD.cellIndex].scope.Width = widh.toString() + "px";
                        }
                    }

                    var rowCount = scope.Dom._BodyElement.rows.length;
                    var cellWidth;
                    if(scope.Dom._HeadChangeWidthTD == scope.Dom._HeadLeftElement.rows[0].cells[0]){
                        cellWidth = scope.CheckColumn.Width;
                        for(var i=0; i<rowCount; i++) {
                            scope.Dom._BodyLeftElement.rows[i].cells[0].children[0].style.width = cellWidth;
                        }
                    }
                    else{
                        var cellIndex = scope.Dom._HeadChangeWidthTD.cellIndex;
                        scope.Columns[cellIndex].scope.$digest();
                        cellWidth = (Number(scope.Columns[cellIndex].scope.Width.replace('px', '')) - 4).toString() + 'px';
                        scope.Dom._BodyElement.children[0].children[cellIndex].setAttribute('width', scope.Columns[cellIndex].scope.Width);
                        for(var i=0; i<rowCount; i++){
                            scope.Dom._BodyElement.rows[i].cells[cellIndex].children[0].style.width = cellWidth;
                        }

                        //保存个性化
                        var tempDiv = document.createElement("div");
                        tempDiv.innerHTML = scope.GridConfig.Columns[cellIndex];
                        tempDiv.children[0].setAttribute("width", cellWidth);
                        scope.GridConfig.setColumn(cellIndex, tempDiv.innerHTML);
                        tempDiv = null;
                    }

                    scope.$digest();

                    scope.Dom._HeadChangeWidthTD = null;
                    scope.Dom._HeadMouseDownX = null;
                    document.body.removeChild(scope.Dom._MouseMoveLine);
                }
            };
            scope._mouseMove = function () {
                if (scope.Dom._IsHeadMouseDown) {
                    scope.Dom._MouseMoveLine.style.left = event.clientX + 'px';
                }
            };

            scope._MoveColumn = {
                ColumnIndex: -1,    //列索引位置
                MoveDiv: null       //mouseMove时显示的图标
            }
            scope._titleMouseDown = function(columnIndex){
                window.addEventListener('mousemove', scope._titleMouseMove, false);
                window.addEventListener('mouseup', scope._titleMouseUp, false);
                scope._MoveColumn.ColumnIndex = columnIndex;
            };
            scope._titleMouseMove = function(){
                if(scope._MoveColumn.ColumnIndex >= 0) {
                    if(scope._MoveColumn.MoveDiv == null){
                        scope._MoveColumn.MoveDiv = document.createElement("div");
                        scope._MoveColumn.MoveDiv.className = "MoveColumnDiv glyphicon glyphicon-chevron-down";
                        scope._MoveColumn.MoveDiv.style.top = (scope.Dom._tableDiv.getBoundingClientRect().top + document.body.scrollTop).toString() + 'px';
                        document.body.appendChild(scope._MoveColumn.MoveDiv);
                    }

                    var scrollYwidth  = scope.Dom._tableDiv.offsetWidth - scope.Dom._tableDiv.clientWidth - 2;
                    var divLeft = scope.Dom._tableDiv.getBoundingClientRect().left;
                    var divRight = scope.Dom._tableDiv.getBoundingClientRect().right - scrollYwidth;
                    if(scope.IsSelect){
                        divLeft = scope.Dom._tableDiv.getBoundingClientRect().left + scope.Dom._HeadLeftElement.offsetWidth;
                    }
                    if(scope.Dom._HeadElement.getBoundingClientRect().right < scope.Dom._tableDiv.getBoundingClientRect().right){
                        divRight = scope.Dom._HeadElement.getBoundingClientRect().right;
                    }
                    if(event.clientX - 5 > divLeft && event.clientX + 5 < divRight){
                        scope._MoveColumn.MoveDiv.style.left = (event.clientX - 5).toString() + 'px';
                    }
                }
            };
            scope._titleMouseUp = function(){
                if(scope._MoveColumn.ColumnIndex >= 0){
                    if(scope._MoveColumn.MoveDiv != null){
                        var moveDivLeft = Number(scope._MoveColumn.MoveDiv.style.left.replace('px', '')) + 5;
                        var cellClientRect;
                        for(var i=0; i<scope.Dom._HeadElement.rows[0].cells.length; i++){
                            cellClientRect = scope.Dom._HeadElement.rows[0].cells[i].getBoundingClientRect();
                            if(moveDivLeft >= cellClientRect.left && moveDivLeft <= cellClientRect.right){
                                if(i != scope._MoveColumn.ColumnIndex && i != scope._MoveColumn.ColumnIndex + 1){
                                    if(scope._MoveColumn.ColumnIndex < i){
                                        scope.Columns.splice(i - 1, 0, scope.Columns.splice(scope._MoveColumn.ColumnIndex, 1)[0]);
                                        scope.GridConfig.moveColumn(scope._MoveColumn.ColumnIndex, i - 1);
                                    }
                                    else{
                                        scope.Columns.splice(i, 0, scope.Columns.splice(scope._MoveColumn.ColumnIndex, 1)[0]);
                                        scope.GridConfig.moveColumn(scope._MoveColumn.ColumnIndex, i);
                                    }
                                    
                                    //移动标题列
                                    scope.Dom._HeadElement.rows[0].cells[i].insertAdjacentElement('beforeBegin', scope.Dom._HeadElement.rows[0].cells[scope._MoveColumn.ColumnIndex]);
                                    //移动表体列
                                    scope.Dom._BodyElement.children[0].children[i].insertAdjacentElement('beforeBegin', scope.Dom._BodyElement.children[0].children[scope._MoveColumn.ColumnIndex]);
                                    for(var j=0; j<scope.Dom._BodyElement.rows.length; j++){
                                        scope.Dom._BodyElement.rows[j].cells[i].insertAdjacentElement('beforeBegin', scope.Dom._BodyElement.rows[j].cells[scope._MoveColumn.ColumnIndex]);
                                    }
                                }
                                break;
                            }
                        }

                        document.body.removeChild(scope._MoveColumn.MoveDiv);
                        scope._MoveColumn.MoveDiv = null;
                    }

                    scope._MoveColumn.ColumnIndex = -1;
                    window.removeEventListener('mousemove', scope._titleMouseMove, false);
                    window.removeEventListener('mouseup', scope._titleMouseUp, false);
                }
            };

            scope.Dom._tableDiv.addEventListener('scroll', scope._scroll, false);
            //对头部TD赋mousedown事件
            scope.Dom._HeadLeftElement.rows[0].cells[0].addEventListener('mousedown', scope._mouseDown, false);
            for (var i = 0; i < scope.Columns.length; i++) {
                var column = scope.Columns[i];
                scope.Dom._BodyElement.children[0].innerHTML += '<col width="' + column.scope.Width + '"/>';
                scope.Dom._HeadElement.rows[0].cells[i].addEventListener('mousedown', scope._mouseDown, false);

                if (!column.scope.IsDisplay) {
                    scope.Dom._BodyElement.children[0].children[i].style.display = 'none';
                }
            }

            //以下是翻页相关
            var pageToolbar = element[0].children[1].children[1];            

            var queryRecordCount = function(completeFun){
                if(scope.module.IsEntityModule){
                    EntityService.queryRecordCount(scope.module.EntityName, scope.Condition,
                        function(count){
                            if(completeFun != undefined && completeFun != null) {
                                completeFun(count);
                            }
                        }
                    );
                }
                else{
                    if(completeFun != undefined && completeFun != null) {
                        completeFun(scope.module.Records.length);
                    }
                }
            };

            scope.$watch(
                function(){
                    return scope.PageNum;
                },
                function(newValue, oldValue){
                    scope.setDisplayPages();
                }
            );

            scope.$watch(
                function(){
                    return scope.PageCount;
                },
                function(){
                    scope.setDisplayPages();
                }
            );

            //侦听事件
            scope.$on("SaveEvent" + scope.module.ID, function(){
                scope.deleteAllRowHtml();
                scope.module.FocusedRecord = null;
                scope.module.load(scope.Condition, scope.OrderBy);
            });

            scope.$on("ReloadEvent" + scope.module.ID, function(){
                scope.deleteAllRowHtml();
                scope.module.Records = new Array();
                scope.module.FocusedRecord = null;

                if(scope.IsAutoLoad){
                    scope.module.load(scope.Condition, scope.OrderBy);
                }
                else{
                    scope.RecordCount = 0;
                    if(scope.module.LoadMode == BaseEnum.LoadMode.CacheAndPaging){                        
                        scope.PageRecords = new Array();
                        scope.PageRecords[0] = scope.module.Records;
                    }
                }
            });

            scope.$on("OnLoadEvent" + scope.module.ID, function(){
                scope.deleteAllRowHtml();
                scope.module.FocusedRecord = null;

                if(!scope.module.IsEntityModule && scope.DataGrid_OrderBy != null){
                    scope.module.sort(scope.DataGrid_OrderBy);
                }

                if(scope.module.LoadMode == BaseEnum.LoadMode.CacheAndPaging){
                    queryRecordCount(function(recordCount) {
                        scope.RecordCount = recordCount;
                        scope.PageRecords = new Array(scope.PageCount);
                        scope.PageRecords[0] = scope.module.Records;

                        if(scope.PageCount > 0){
                            scope.assignPage(0);
                        }
                    });
                }
                else if(scope.module.LoadMode == BaseEnum.LoadMode.CacheAndNoPaging){
                    scope.RecordCount = scope.module.Records.length;
                    if(scope.PageCount > 0){
                        scope.assignPage(0);
                    }
                }
            });

            scope.$on("DeleteEvent" + scope.module.ID, function(event, records){
                queryRecordCount(function(recordCount) {
                    scope.RecordCount = recordCount;
                    if(scope.module.LoadMode == BaseEnum.LoadMode.CacheAndPaging){
                        scope.module.load(scope.Condition, scope.OrderBy);
                    }
                    else{
                        if(scope.PageCount > 0){
                            scope.assignPage(scope.PageNum);
                        }
                        else{
                            scope.deleteAllRowHtml();
                            scope.module.FocusedRecord = null;
                        }
                    }
                });
            });

            scope.$on("RowsDataChangeEvent" + scope.module.ID, function(event, records){
                if(records == undefined) {
                    records = [scope.module.FocusedRecord];
                }
                scope.refreshRows(records);
            });

            scope.$on("RowsDeleteEvent" + scope.module.ID, function(event, records){
                if(records == undefined) {
                    records = [scope.module.FocusedRecord];
                }
                scope.refreshDeleteRows(records);
            });
            //刷新
            scope.$on("RefreshEvent" + scope.module.ID, function(event, records){
                scope.deleteAllRowHtml();
                scope.RecordCount = scope.module.Records.length;
                if(scope.RecordCount > 0){
                    scope.assignPage(0);
                }
            });
            //刷新当前页
            scope.$on("RefreshCurrentPageEvent" + scope.module.ID, function(event, records){
                scope.deleteAllRowHtml();
                scope.RecordCount = scope.module.Records.length;
                scope.assignPage(scope.PageNum);
            });

            //初次加载数据
            if(scope.module != undefined && scope.module != null){
                if(scope.IsAutoLoad && scope.module.ParentModule == null){
                    if(scope.module.IsEntityModule){
                        scope.module.load(scope.Condition, scope.OrderBy);
                    }
                    else{
                        scope.RecordCount = scope.module.Records.length;

                        if(scope.RecordCount > 0){
                            scope.firstPage();
                        }                    
                    }
                }
            }
        }
    }
}])

.directive("textboxcolumn", ['BaseEnum', function(BaseEnum) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
            '<td ng-show="IsDisplay">' +
                '<div style="display: none">' +
                    '<TextBox class="GridBaseControl" change="change()" blur="blur()" value="value" isempty="{{scope.IsEmpty.toString()}}"></TextBox>' +
                '</div>' +
                '<div style="width: {{DivWidth}}" ng-click="order()">' +
                    '<u ng-if="IsTitleClick" style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                    '<span ng-if="!IsTitleClick">{{DisplayName}}</span>' +
                    '<div class="DT_EmptyDiv" ng-show="!IsEmpty">*</div>' +
                    '<i ng-if="IsOrder">&nbsp;</i>' +
                    '<span ng-if="IsOrder" ng-class="SortClass">' +
                '</div>' +
            '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControllType = BaseEnum.ControllType.TextBox;
            scope.TextAlignClass = 'TextLeftAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.SortValue = BaseEnum.SortType.Empty.Value;
            scope.SortClass = "";
            scope.BindField = "";

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }
            if (attrs["bindfield"] != undefined && attrs["bindfield"].trim() != "") {
                scope.BindField = attrs["bindfield"].trim();
            }

            //实体类型，不是全加载，自定义字段不允许排序
            if(scope.IsOrder && scope.ValueField.indexOf('_') == 0 && 
                dataGridCtrl.scope.module.IsEntityModule && dataGridCtrl.scope.module.LoadMode != BaseEnum.LoadMode.CacheAndNoPaging){
                scope.IsOrder = false;
            }

            if(scope.IsOrder){
                var sortValue = null;
                if(dataGridCtrl.scope.DataGrid_OrderBy && dataGridCtrl.scope.DataGrid_OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.DataGrid_OrderBy[scope.ValueField];
                }
                else if(dataGridCtrl.scope.module.OrderBy && dataGridCtrl.scope.module.OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.module.OrderBy[scope.ValueField];
                }
                if(sortValue){
                    var spanElement = element[0].children[1].lastElementChild;
                    scope.SortValue = sortValue;
                    if(sortValue == 1){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(sortValue == -1){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                }
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function(){
                scope.titleclick();
            };
            scope.order = function(){
                if(scope.IsOrder){
                    var spanElement = element[0].children[1].lastElementChild;
                    if(scope.SortValue == BaseEnum.SortType.Empty.Value){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Asc.Value){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Desc.Value){
                        scope.SortValue = BaseEnum.SortType.Empty.Value;
                        scope.SortClass = "";
                    }
                    dataGridCtrl.scope.setOrderBy(scope.ValueField, scope.SortValue);
                    dataGridCtrl.scope.loadByOrder();
                }
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                scope.value = scope.value.trim();
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") >= 0){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = record[scope.ValueField];
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = '" + scope.value + "'");
                    dataGridCtrl.scope.cellValueChange(scope.ValueField, scope.value, oldValue);
                }
            };
            scope.blur = function(){
                var td = event.srcElement.parentNode;
                element[0].children[0].appendChild(event.srcElement);
                if(scope.value != undefined && scope.value != null && scope.value !== '') {
                    td.children[0].innerText = scope.value;
                    td.children[0].setAttribute("title", scope.value);
                }
                else{
                    td.children[0].removeAttribute("title");
                    td.children[0].innerHTML = '&nbsp;';
                }
                td.children[0].style.display = '';
            };

            element[0].children[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );
            element[0].children[1].addEventListener('mousedown',
                function(){
                    dataGridCtrl.scope._titleMouseDown(element[0].cellIndex);
                },
                false
            );

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isedit"];
                },
                function(){
                    if(attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsEdit = false;
                    }
                    else{
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}])

.directive("numberboxcolumn", ['BaseEnum', 'BaseClass', function(BaseEnum, BaseClass) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
            '<td>' +
                '<div style="display: none">' +
                    '<NumberBox class="GridBaseControl" change="change()" blur="blur()" value="value" isempty="{{scope.IsEmpty.toString()}}"></NumberBox>' +
                '</div>' +
                '<div style="width: {{DivWidth}}" ng-click="order()">' +
                    '<u ng-if="IsTitleClick" style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                    '<span ng-if="!IsTitleClick">{{DisplayName}}</span>' +
                    '<div class="DT_EmptyDiv" ng-show="!IsEmpty">*</div>' +
                    '<i ng-if="IsOrder">&nbsp;</i>' +
                    '<span ng-if="IsOrder" ng-class="SortClass"/>' +
                '</div>' +
            '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControllType = BaseEnum.ControllType.NumberBox;
            scope.TextAlignClass = 'TextRightAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.SortValue = BaseEnum.SortType.Empty.Value;
            scope.SortClass = "";
            scope.RoundSet = null;
            scope.MinValue = null;
            scope.MaxValue = null;
            scope.TotalType = null;     //Excel列汇总类型
            scope.BindField = "";

            if (attrs["round"] != undefined && attrs["round"].trim() != "") {
                scope.RoundSet = eval("(" + attrs["round"].trim() + ")");
            }
            if (attrs["minvalue"] != undefined && attrs["minvalue"].trim() != "") {
                scope.MinValue = parseFloat(attrs["minvalue"].trim());
            }
            if (attrs["maxvalue"] != undefined && attrs["maxvalue"].trim() != "") {
                scope.MaxValue = parseFloat(attrs["maxvalue"].trim());
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["totaltype"] != undefined && attrs["totaltype"].trim() != "") {
                if(attrs["totaltype"].trim() == '0' || attrs["totaltype"].trim().toLocaleLowerCase() == 'sum'){
                    scope.TotalType = BaseEnum.TotalType.Sum;
                }
                if(attrs["totaltype"].trim() == '1' || attrs["totaltype"].trim().toLocaleLowerCase().indexOf('ave') == 0){
                    scope.TotalType = BaseEnum.TotalType.Average;
                }
            }
            if (attrs["bindfield"] != undefined && attrs["bindfield"].trim() != "") {
                scope.BindField = attrs["bindfield"].trim();
            }

            scope.$$childHead.MinValue = scope.MinValue;
            scope.$$childHead.MaxValue = scope.MaxValue;
            scope.$$childHead.IsEmpty = scope.IsEmpty;

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }
            if(scope.IsOrder && scope.ValueField.indexOf('_') == 0 && 
                dataGridCtrl.scope.module.IsEntityModule && dataGridCtrl.scope.module.LoadMode != BaseEnum.LoadMode.CacheAndNoPaging){
                scope.IsOrder = false;
            }

            if(scope.IsOrder){
                var sortValue = null;
                if(dataGridCtrl.scope.DataGrid_OrderBy && dataGridCtrl.scope.DataGrid_OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.DataGrid_OrderBy[scope.ValueField];
                }
                else if(dataGridCtrl.scope.module.OrderBy && dataGridCtrl.scope.module.OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.module.OrderBy[scope.ValueField];
                }
                if(sortValue){
                    var spanElement = element[0].children[1].lastElementChild;
                    scope.SortValue = sortValue;
                    if(sortValue == 1){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(sortValue == -1){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                }
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function () {
                scope.titleclick();
            };
            scope.order = function(){
                if(scope.IsOrder){
                    var spanElement = element[0].children[1].lastElementChild;
                    if(scope.SortValue == BaseEnum.SortType.Empty.Value){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Asc.Value){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Desc.Value){
                        scope.SortValue = BaseEnum.SortType.Empty.Value;
                        scope.SortClass = "";
                    }

                    dataGridCtrl.scope.setOrderBy(scope.ValueField, scope.SortValue);
                    dataGridCtrl.scope.loadByOrder();
                }
            };

            scope.keyDown = function () {
                dataGridCtrl.scope.keyDown();
                if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") >= 0){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = record[scope.ValueField];
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = " + scope.value.toString());
                    dataGridCtrl.scope.cellValueChange(scope.ValueField, scope.value, oldValue);
                }
            };
            scope.blur = function () {
                var td = event.srcElement.parentNode;
                element[0].children[0].appendChild(event.srcElement);
                if(event.srcElement.value != '') {
                    if(scope.Round != null){
                        td.children[0].innerText = scope.Round.formatNumber(scope.value);
                    }
                    else{
                        td.children[0].innerText = scope.value;
                    }
                    td.children[0].setAttribute("title", td.children[0].innerText);
                }
                else{
                    td.children[0].innerHTML = '&nbsp;';
                    td.children[0].removeAttribute("title");
                }
                
                td.children[0].style.display = '';
            };
            scope.getRound = function(record){
                if(!record){
                    record = dataGridCtrl.scope.module.FocusedRecord;
                }
                if(scope.RoundSet != null){
                    var precision, 
                        roundType = BaseEnum.RoundType.AccondValueRound.Value, 
                        roundValue = 5;

                    if(scope.RoundSet.Precision.constructor === Number){
                        precision = scope.RoundSet.Precision;
                    }
                    else{
                        try{
                            precision = eval("record." + scope.RoundSet.Precision);
                        }
                        catch(e){
                            return null;
                        }
                    }
                    

                    if(scope.RoundSet.RoundType != undefined && scope.RoundSet.RoundType != null){
                        if(scope.RoundSet.RoundType.constructor === Number){
                            roundType = scope.RoundSet.RoundType;
                        }
                        else{
                            try{
                                roundType = eval("record." + scope.RoundSet.RoundType);
                            }
                            catch(e){
                            }
                        }
                    }

                    if(scope.RoundSet.RoundValue != undefined && scope.RoundSet.RoundValue != null){
                        if(scope.RoundSet.RoundValue.constructor === Number){
                            roundValue = scope.RoundSet.RoundValue;
                        }
                        else{
                            try{
                                roundValue = eval("record." + scope.RoundSet.RoundValue);
                            }
                            catch(e){
                            }
                        }
                    }

                    return new BaseClass.Round(precision, roundType, roundValue);
                }
                else{
                    return null;
                }
            };
            scope.__defineGetter__('Round', function(){
                return scope.getRound();
            });
            scope.setBoxRound = function(record){
                scope.$$childHead.Round = scope.getRound(record);
            };

            element[0].children[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );
            element[0].children[1].addEventListener('mousedown',
                function(){
                    dataGridCtrl.scope._titleMouseDown(element[0].cellIndex);
                },
                false
            );

            if(scope.RoundSet != null){
                var setCellText = function(){
                    var focusedRecord = dataGridCtrl.scope.module.FocusedRecord;
                    var rowIndex = dataGridCtrl.scope.getRowIndex(focusedRecord._id);
                    var cellIndex = dataGridCtrl.scope.getCellIndex(scope.ValueField);
                    var value = scope.Round.formatNumber(parseFloat(dataGridCtrl.scope.module.FocusedRecord[scope.ValueField]));
                    dataGridCtrl.scope.module.FocusedRecord[scope.ValueField] = value;
                    dataGridCtrl.scope.setCellText(rowIndex, cellIndex, value);
                };
                var precisionFieldName;
                if(scope.RoundSet.Precision != null && scope.RoundSet.Precision.constructor === String){
                    precisionFieldName = scope.RoundSet.Precision;
                    if(precisionFieldName.indexOf(".")){
                        precisionFieldName = precisionFieldName.split(".")[0];
                    }
                    dataGridCtrl.scope.EventManage.addListener("onChange_" + precisionFieldName, setCellText);
                }
                var roundTypeFieldName;
                if(scope.RoundSet.RoundType != null && scope.RoundSet.RoundType.constructor === String){
                    roundTypeFieldName = scope.RoundSet.RoundType;
                    if(roundTypeFieldName.indexOf(".")){
                        roundTypeFieldName = roundTypeFieldName.split(".")[0];
                    }
                    if(roundTypeFieldName != precisionFieldName){
                        dataGridCtrl.scope.EventManage.addListener("onChange_" + roundTypeFieldName, setCellText);
                    }
                }
                var roundValueFieldName;
                if(scope.RoundSet.RoundValue != null && scope.RoundSet.RoundValue.constructor === String){
                    roundValueFieldName = scope.RoundSet.RoundValue;
                    if(roundValueFieldName.indexOf(".")){
                        roundValueFieldName = roundValueFieldName.split(".")[0];
                    }
                    if(roundValueFieldName != roundTypeFieldName && roundValueFieldName != precisionFieldName){
                        dataGridCtrl.scope.EventManage.addListener("onChange_" + roundTypeFieldName, setCellText);
                    }
                }
            }

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function () {
                    return attrs["isedit"];
                },
                function () {
                    if (attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false') {
                        scope.IsEdit = false;
                    }
                    else {
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function () {
                    return attrs["isdisplay"];
                },
                function () {
                    if (attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false') {
                        scope.IsDisplay = false;
                    }
                    else {
                        scope.IsDisplay = true;
                    }
                }
            );            
        }
    }
}])

.directive("percentboxcolumn", ['BaseEnum', 'BaseClass', function(BaseEnum, BaseClass) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
        '<td ng-show="IsDisplay">' +
            '<div style="display: none">' +
                '<PercentBox class="GridBaseControl" change="change()" blur="blur()" value="value" isempty="{{scope.IsEmpty.toString()}}"></PercentBox>' +
            '</div>' +
            '<div style="width: {{DivWidth}}" ng-click="order()">' +
                '<u ng-if="IsTitleClick" style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                '<span ng-if="!IsTitleClick">{{DisplayName}}</span>' +
                '<div class="DT_EmptyDiv" ng-show="!IsEmpty">*</div>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" ng-class="SortClass"/>' +
            '</div>' +
        '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControllType = BaseEnum.ControllType.PercentBox;
            scope.TextAlignClass = 'TextRightAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.SortValue = BaseEnum.SortType.Empty.Value;
            scope.SortClass = "";
            scope.RoundSet = null;
            scope.MinValue = null;
            scope.MaxValue = null;
            scope.TotalType = null;     //Excel列汇总类型
            scope.BindField = "";

            if (attrs["round"] != undefined && attrs["round"].trim() != "") {
                scope.RoundSet = eval("(" + attrs["round"].trim() + ")");
            }
            if (attrs["minvalue"] != undefined && attrs["minvalue"].trim() != "") {
                scope.MinValue = parseFloat(attrs["minvalue"].trim());
            }
            if (attrs["maxvalue"] != undefined && attrs["maxvalue"].trim() != "") {
                scope.MaxValue = parseFloat(attrs["maxvalue"].trim());
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["totaltype"] != undefined && attrs["totaltype"].trim() != "") {
                if(attrs["totaltype"].trim() == '0' || attrs["totaltype"].trim().toLocaleLowerCase() == 'sum'){
                    scope.TotalType = BaseEnum.TotalType.Sum;
                }
                if(attrs["totaltype"].trim() == '1' || attrs["totaltype"].trim().toLocaleLowerCase().indexOf('ave') == 0){
                    scope.TotalType = BaseEnum.TotalType.Average;
                }
            }
            if (attrs["bindfield"] != undefined && attrs["bindfield"].trim() != "") {
                scope.BindField = attrs["bindfield"].trim();
            }

            scope.$$childHead.MinValue = scope.MinValue;
            scope.$$childHead.MaxValue = scope.MaxValue;
            scope.$$childHead.IsEmpty = scope.IsEmpty;

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }

            if(scope.IsOrder && scope.ValueField.indexOf('_') == 0 && 
                dataGridCtrl.scope.module.IsEntityModule && dataGridCtrl.scope.module.LoadMode != BaseEnum.LoadMode.CacheAndNoPaging){
                scope.IsOrder = false;
            }

            if(scope.IsOrder){
                var sortValue = null;
                if(dataGridCtrl.scope.DataGrid_OrderBy && dataGridCtrl.scope.DataGrid_OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.DataGrid_OrderBy[scope.ValueField];
                }
                else if(dataGridCtrl.scope.module.OrderBy && dataGridCtrl.scope.module.OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.module.OrderBy[scope.ValueField];
                }
                if(sortValue){
                    var spanElement = element[0].children[1].lastElementChild;
                    scope.SortValue = sortValue;
                    if(sortValue == 1){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(sortValue == -1){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                }
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function () {
                scope.titleclick();
            };
            scope.order = function(){
                if(scope.IsOrder){
                    var spanElement = element[0].children[1].lastElementChild;
                    if(scope.SortValue == BaseEnum.SortType.Empty.Value){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Asc.Value){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Desc.Value){
                        scope.SortValue = BaseEnum.SortType.Empty.Value;
                        scope.SortClass = "";
                    }
                    dataGridCtrl.scope.setOrderBy(scope.ValueField, scope.SortValue);
                    dataGridCtrl.scope.loadByOrder();
                }
            };            

            scope.keyDown = function () {
                dataGridCtrl.scope.keyDown();
                if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") >= 0){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = record[scope.ValueField];
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = " + scope.value.toString());
                    dataGridCtrl.scope.cellValueChange(scope.ValueField, scope.value, oldValue);
                }
            };
            scope.blur = function () {
                var td = event.srcElement.parentNode;
                element[0].children[0].appendChild(event.srcElement);
                if(event.srcElement.value != '') {
                    if(scope.Round != null){
                        td.children[0].innerText = scope.Round.formatPercent(scope.value);
                    }
                    else{
                        td.children[0].innerText = $scope.value;
                    }
                    td.children[0].setAttribute("title", td.children[0].innerText);
                }
                else{
                    td.children[0].innerHTML = '&nbsp;';
                    td.children[0].removeAttribute("title");
                }
                td.children[0].style.display = '';
            };

            scope.getRound = function(record){
                if(!record){
                    record = dataGridCtrl.scope.module.FocusedRecord;
                }
                if(scope.RoundSet != null){
                    var precision, 
                        roundType = BaseEnum.RoundType.AccondValueRound.Value, 
                        roundValue = 5;

                    if(scope.RoundSet.Precision.constructor === Number){
                        precision = scope.RoundSet.Precision;
                    }
                    else{
                        try{
                            precision = eval("record." + scope.RoundSet.Precision);
                        }
                        catch(e){
                            return null;
                        }
                    }
                    

                    if(scope.RoundSet.RoundType != undefined && scope.RoundSet.RoundType != null){
                        if(scope.RoundSet.RoundType.constructor === Number){
                            roundType = scope.RoundSet.RoundType;
                        }
                        else{
                            try{
                                roundType = eval("record." + scope.RoundSet.RoundType);
                            }
                            catch(e){
                            }
                        }
                    }

                    if(scope.RoundSet.RoundValue != undefined && scope.RoundSet.RoundValue != null){
                        if(scope.RoundSet.RoundValue.constructor === Number){
                            roundValue = scope.RoundSet.RoundValue;
                        }
                        else{
                            try{
                                roundValue = eval("record." + scope.RoundSet.RoundValue);
                            }
                            catch(e){
                            }
                        }
                    }

                    return new BaseClass.Round(precision, roundType, roundValue);
                }
                else{
                    return null;
                }
            };
            scope.__defineGetter__('Round', function(){
                return scope.getRound();
            });
            scope.setBoxRound = function(record){
                scope.$$childHead.Round = scope.getRound(record);
            };

            element[0].children[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );
            element[0].children[1].addEventListener('mousedown',
                function(){
                    dataGridCtrl.scope._titleMouseDown(element[0].cellIndex);
                },
                false
            );

            if(scope.RoundSet != null){
                var setCellText = function(){
                    var focusedRecord = dataGridCtrl.scope.module.FocusedRecord;
                    var rowIndex = dataGridCtrl.scope.getRowIndex(focusedRecord._id);
                    var cellIndex = dataGridCtrl.scope.getCellIndex(scope.ValueField);
                    var value = scope.Round.formatNumber(focusedRecord[scope.ValueField]);
                    dataGridCtrl.scope.module.FocusedRecord[scope.ValueField] = value;
                    dataGridCtrl.scope.setCellText(rowIndex, cellIndex, scope.Round.formatPercent(value));
                };
                var precisionFieldName;
                if(scope.RoundSet.Precision != null && scope.RoundSet.Precision.constructor === String){
                    precisionFieldName = scope.RoundSet.Precision;
                    if(precisionFieldName.indexOf(".")){
                        precisionFieldName = precisionFieldName.split(".")[0];
                    }
                    dataGridCtrl.scope.EventManage.addListener("onChange_" + precisionFieldName, setCellText);
                }
                var roundTypeFieldName;
                if(scope.RoundSet.RoundType != null && scope.RoundSet.RoundType.constructor === String){
                    roundTypeFieldName = scope.RoundSet.RoundType;
                    if(roundTypeFieldName.indexOf(".")){
                        roundTypeFieldName = roundTypeFieldName.split(".")[0];
                    }
                    if(roundTypeFieldName != precisionFieldName){
                        dataGridCtrl.scope.EventManage.addListener("onChange_" + roundTypeFieldName, setCellText);
                    }
                }
                var roundValueFieldName;
                if(scope.RoundSet.RoundValue != null && scope.RoundSet.RoundValue.constructor === String){
                    roundValueFieldName = scope.RoundSet.RoundValue;
                    if(roundValueFieldName.indexOf(".")){
                        roundValueFieldName = roundValueFieldName.split(".")[0];
                    }
                    if(roundValueFieldName != roundTypeFieldName && roundValueFieldName != precisionFieldName){
                        dataGridCtrl.scope.EventManage.addListener("onChange_" + roundTypeFieldName, setCellText);
                    }
                }
            }

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function () {
                    return attrs["isedit"];
                },
                function () {
                    if (attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false') {
                        scope.IsEdit = false;
                    }
                    else {
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function () {
                    return attrs["isdisplay"];
                },
                function () {
                    if (attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false') {
                        scope.IsDisplay = false;
                    }
                    else {
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}])

.directive("checkboxcolumn", ['BaseEnum', function(BaseEnum) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
        '<td ng-show="IsDisplay">' +
            '<div style="display: none">' +
                '<CheckBox blur="blur()" change="change()" style="outline:none;" value="value"></CheckBox>' +
            '</div>' +
            '<div style="width: {{DivWidth}}" ng-click="order()">' +
                '<u ng-if="IsTitleClick" style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                '<span ng-if="!IsTitleClick">{{DisplayName}}</span>' +
                '<div class="DT_EmptyDiv" ng-show="!IsEmpty">*</div>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" ng-class="SortClass"/>' +
            '</div>' +
        '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.Data = {value: false};
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControllType = BaseEnum.ControllType.CheckBox;
            scope.TextAlignClass = 'TextCenterAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.SortValue = BaseEnum.SortType.Empty.Value;
            scope.SortClass = "";
            scope.BindField = "";

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }
            if (attrs["bindfield"] != undefined && attrs["bindfield"].trim() != "") {
                scope.BindField = attrs["bindfield"].trim();
            }

            if(scope.IsOrder && scope.ValueField.indexOf('_') == 0 && 
                dataGridCtrl.scope.module.IsEntityModule && dataGridCtrl.scope.module.LoadMode != BaseEnum.LoadMode.CacheAndNoPaging){
                scope.IsOrder = false;
            }

            if(scope.IsOrder){
                var sortValue = null;
                if(dataGridCtrl.scope.DataGrid_OrderBy && dataGridCtrl.scope.DataGrid_OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.DataGrid_OrderBy[scope.ValueField];
                }
                else if(dataGridCtrl.scope.module.OrderBy && dataGridCtrl.scope.module.OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.module.OrderBy[scope.ValueField];
                }
                if(sortValue){
                    var spanElement = element[0].children[1].lastElementChild;
                    scope.SortValue = sortValue;
                    if(sortValue == 1){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(sortValue == -1){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                }
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function(){
                scope.titleclick();
            };

            scope.order = function(){
                if(scope.IsOrder){
                    var spanElement = element[0].children[1].lastElementChild;
                    if(scope.SortValue == BaseEnum.SortType.Empty.Value){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Asc.Value){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Desc.Value){
                        scope.SortValue = BaseEnum.SortType.Empty.Value;
                        scope.SortClass = "";
                    }
                    dataGridCtrl.scope.setOrderBy(scope.ValueField, scope.SortValue);
                    dataGridCtrl.scope.loadByOrder();
                }
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 32 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") >= 0){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = record[scope.ValueField];
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = " + scope.value.toString());
                    dataGridCtrl.scope.cellValueChange(scope.ValueField, scope.value, oldValue);
                }
            };
            scope.blur = function(){
                var td = event.srcElement.parentNode;
                element[0].children[0].appendChild(event.srcElement);
                if(scope.value) {
                    td.children[0].innerHTML = '<div class="Hook"/>'; //'&radic;';
                }
                else{
                    td.children[0].innerHTML = '&nbsp;';
                }
                td.children[0].style.display = '';
            };

            element[0].children[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );
            element[0].children[1].addEventListener('mousedown',
                function(){
                    dataGridCtrl.scope._titleMouseDown(element[0].cellIndex);
                },
                false
            );

            scope.$watch(
                function(){
                    return scope.value;
                },
                function(){
                    scope.Data.value = scope.value;
                }
            );
            scope.$watch(
                function(){
                    return scope.Data.value;
                },
                function(){
                    scope.value = scope.Data.value;
                }
            );
            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isedit"];
                },
                function(){
                    if(attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsEdit = false;
                    }
                    else{
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}])

.directive("calendarcolumn", ['$compile', 'BaseEnum', 'BaseFunction', function($compile, BaseEnum, BaseFunction) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
        '<td ng-show="IsDisplay">' +
            '<div style="display: none">' +
                '<Calendar class="GridBaseControl" change="change()" blur="blur()" style="overflow: visible;" Format="{{Format == BaseEnum.DateTimeFormat.Date ? \'Data\' : \'DateTime\'}}" value="value" isempty="{{scope.IsEmpty.toString()}}" isgrid="true"></Calendar>' +
            '</div>' +
            '<div style="width: {{DivWidth}}" ng-click="order()">' +
                '<u ng-if="IsTitleClick" style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                '<span ng-if="!IsTitleClick">{{DisplayName}}</span>' +
                '<div class="DT_EmptyDiv" ng-show="!IsEmpty">*</div>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" ng-class="SortClass"/>' +
            '</div>' +
        '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControllType = BaseEnum.ControllType.Calendar;
            scope.TextAlignClass = 'TextLeftAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.SortValue = BaseEnum.SortType.Empty.Value;
            scope.SortClass = "";
            scope.Format = BaseEnum.DateTimeFormat.DateTime;
            scope.IsControlDisplay = false;            
            scope.CurrentCell = null;
            scope.BindField = "";

            if (attrs["format"] && attrs["format"].toLocaleLowerCase().trim() == "date") {
                scope.Format = BaseEnum.DateTimeFormat.Date;
            }
            if (attrs["displayname"] && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["isempty"] && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["istitleclick"] && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }
            if (attrs["bindfield"] != undefined && attrs["bindfield"].trim() != "") {
                scope.BindField = attrs["bindfield"].trim();
            }

            if(scope.IsOrder && scope.ValueField.indexOf('_') == 0 && 
                dataGridCtrl.scope.module.IsEntityModule && dataGridCtrl.scope.module.LoadMode != BaseEnum.LoadMode.CacheAndNoPaging){
                scope.IsOrder = false;
            }

            if(scope.IsOrder){
                var sortValue = null;
                if(dataGridCtrl.scope.DataGrid_OrderBy && dataGridCtrl.scope.DataGrid_OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.DataGrid_OrderBy[scope.ValueField];
                }
                else if(dataGridCtrl.scope.module.OrderBy && dataGridCtrl.scope.module.OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.module.OrderBy[scope.ValueField];
                }
                if(sortValue){
                    var spanElement = element[0].children[1].lastElementChild;
                    scope.SortValue = sortValue;
                    if(sortValue == 1){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(sortValue == -1){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                }
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function(){
                scope.titleclick();
            };

            scope.order = function(){
                if(scope.IsOrder){
                    var spanElement = element[0].children[1].lastElementChild;
                    if(scope.SortValue == BaseEnum.SortType.Empty.Value){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Asc.Value){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Desc.Value){
                        scope.SortValue = BaseEnum.SortType.Empty.Value;
                        scope.SortClass = "";
                    }
                    dataGridCtrl.scope.setOrderBy(scope.ValueField, scope.SortValue);
                    dataGridCtrl.scope.loadByOrder();
                }
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") >= 0){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = record[scope.ValueField];
                if(oldValue !== scope.value) {
                    record[scope.ValueField] = scope.value;
                    dataGridCtrl.scope.cellValueChange(scope.ValueField, scope.value, oldValue);
                }
            };
            scope.blur = function(){
                var tdElement = scope.CurrentCell;

                element[0].children[0].appendChild(tdElement.children[1]);
                if(scope.value && scope.value != '') {
                    tdElement.children[0].innerText = BaseFunction.dateTimeToString(new Date(scope.value), scope.Format);
                    tdElement.children[0].setAttribute("title", tdElement.children[0].innerText);
                }
                else{
                    tdElement.children[0].innerHTML = '&nbsp;';
                    tdElement.children[0].removeAttribute("title");
                }
                tdElement.children[0].style.display = '';
                scope.CurrentCell = null;
            };

            setTimeout(function(){
                element[0].children[0].children[0].addEventListener('keydown', scope.keyDown, false);
                element[0].children[1].addEventListener('mousedown',
                    function(){
                        dataGridCtrl.scope._titleMouseDown(element[0].cellIndex);
                    },
                    false
                );
            }, 1);

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isedit"];
                },
                function(){
                    if(attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsEdit = false;
                    }
                    else{
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}])

.directive("refercolumn", ['$compile','BaseEnum', 'BaseFunction', function($compile, BaseEnum, BaseFunction) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&',
            beforeshow: '&'
        },
        template:
        '<td ng-show="IsDisplay">' +
            '<div style="display: none" ng-transclude>' +
            '</div>' +
            '<div style="width: {{DivWidth}}" ng-click="order()">' +
                '<u ng-if="IsTitleClick" style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                '<span ng-if="!IsTitleClick">{{DisplayName}}</span>' +
                '<div class="DT_EmptyDiv" ng-show="!IsEmpty">*</div>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" ng-class="SortClass"/>' +
            '</div>' +
        '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.KeyField = '_id';
            scope.CodeField = 'Code';
            scope.TextField = 'Name';
            scope.ValueField = '';
            scope.EntityName;
            scope.WindowTitle;
            scope.IsSelect = false;
            scope.Condition = null;
            scope.OrderBy = null;
            scope.Populate = "";

            scope.ControllType = BaseEnum.ControllType.Refer;
            scope.TextAlignClass = 'TextLeftAlign';

            scope.IsEdit = true;
            scope.IsDisplay = true;            
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '100px';
            scope.DivWidth;
            scope.IsTitleClick = false;            
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.SortValue = BaseEnum.SortType.Empty.Value;
            scope.SortClass = "";
            scope.IsControlDisplay = false;
            scope.Element;
            scope.Columns = [];
            scope.BindField = "";

            if (attrs["entityname"] != undefined && attrs["entityname"].trim() != "") {
                scope.EntityName = attrs["entityname"].trim();
                scope.ValueField = scope.EntityName;
            }
            if (attrs["keyfield"] != undefined && attrs["keyfield"].trim() != "") {
                scope.KeyField = attrs["keyfield"].trim();
            }
            if (attrs["codefield"] != undefined && attrs["codefield"].trim() != "") {
                scope.CodeField = attrs["codefield"].trim();
            }
            if (attrs["textfield"] != undefined && attrs["textfield"].trim() != "") {
                scope.TextField = attrs["textfield"].trim();
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            
            if (attrs["windowtitle"] != undefined && attrs["windowtitle"].trim() != "") {
                scope.WindowTitle = attrs["windowtitle"].trim();
            }
            if (attrs["isselect"] != undefined && attrs["isselect"].toLocaleLowerCase() == "true") {
                scope.IsSelect = true;
            }

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }
            if (attrs["condition"] != undefined && attrs["condition"].trim() != "") {
                scope.Condition = attrs["condition"].trim();
            }
            if (attrs["orderby"] != undefined && attrs["orderby"].trim() != "") {
                scope.OrderBy = attrs["orderby"].trim();
            }
            if (attrs["populate"] != undefined && attrs["populate"].trim() != "") {
                scope.Populate = attrs["populate"].trim();
            }
            if (attrs["bindfield"] != undefined && attrs["bindfield"].trim() != "") {
                scope.BindField = attrs["bindfield"].trim();
            }

            if(scope.IsOrder && scope.ValueField.indexOf('_') == 0 && 
                dataGridCtrl.scope.module.IsEntityModule && dataGridCtrl.scope.module.LoadMode != BaseEnum.LoadMode.CacheAndNoPaging){
                scope.IsOrder = false;
            }

            if(scope.IsOrder){
                var sortValue = null;
                if(dataGridCtrl.scope.DataGrid_OrderBy && dataGridCtrl.scope.DataGrid_OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.DataGrid_OrderBy[scope.ValueField];
                }
                else if(dataGridCtrl.scope.module.OrderBy && dataGridCtrl.scope.module.OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.module.OrderBy[scope.ValueField];
                }
                if(sortValue){
                    var spanElement = element[0].children[1].lastElementChild;
                    scope.SortValue = sortValue;
                    if(sortValue == 1){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(sortValue == -1){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                }
            }

            scope.titleClick = function(){
                scope.titleclick();
            };

            scope.order = function(){
                if(scope.IsOrder){
                    var spanElement = element[0].children[1].lastElementChild;
                    if(scope.SortValue == BaseEnum.SortType.Empty.Value){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Asc.Value){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Desc.Value){
                        scope.SortValue = BaseEnum.SortType.Empty.Value;
                        scope.SortClass = "";
                    }
                    dataGridCtrl.scope.setOrderBy(scope.ValueField, scope.SortValue);
                    dataGridCtrl.scope.loadByOrder();
                }
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(refRecords){
                var focusedRecord = dataGridCtrl.scope.module.FocusedRecord;
                var rowIndex = dataGridCtrl.scope.getRowIndex(focusedRecord._id);
                var oldValue = Object.assign({}, dataGridCtrl.scope.module.FocusedRecord[scope.ValueField]);

                var record;
                var currentRecordIndex = dataGridCtrl.scope.module.getRecordIndex(dataGridCtrl.scope.module.FocusedRecord);
                var currentRowIndex = dataGridCtrl.scope.getRowIndex(focusedRecord._id);
                for (var i=0; i<refRecords.length; i++) {
                    if(dataGridCtrl.scope.module.Records.length-1 < currentRecordIndex){
                        record = dataGridCtrl.scope.module.add();
                        dataGridCtrl.scope.RecordCount++;
                        record[scope.ValueField] = refRecords[i];

                        if(currentRowIndex < dataGridCtrl.scope.module.PageSize){
                            dataGridCtrl.scope.addRowHtml(record);
                        }
                    }
                    else{
                        record = dataGridCtrl.scope.module.Records[currentRecordIndex];
                        record[scope.ValueField] = refRecords[i];
                        if(currentRowIndex < dataGridCtrl.scope.module.PageSize){
                            // dataGridCtrl.scope.refreshRows([record]);
                        }
                    }
                    currentRecordIndex++;
                    currentRowIndex++;
                };

                dataGridCtrl.scope.cellValueChange(scope.ValueField, refRecords, oldValue);
            };
            scope.blur = function(){
                var tdElement = scope.Element.parentNode;
                element[0].children[0].appendChild(scope.Element);
                if(scope.value != undefined && scope.value != null && 
                    scope.value[scope.KeyField] != undefined && scope.value[scope.KeyField] != null) {
                    tdElement.children[0].innerText = scope.value[scope.TextField];
                    tdElement.children[0].setAttribute("title", scope.value[scope.TextField]);
                }
                else{
                    tdElement.children[0].innerHTML = '&nbsp;';
                    tdElement.children[0].removeAttribute("title");
                }
                tdElement.children[0].style.display = '';
            };
            scope.beforeShow = function(refScope){
                return scope.beforeshow({refScope: refScope});
            };

            var refDivElement = element[0].children[0];
            var referHtml = '<Refer class="GridBaseControl" beforeshow="beforeShow(refScope)" Condition="' + scope.Condition + '" OrderBy="' + scope.OrderBy + '" Populate="' + scope.Populate + '"';
            referHtml += ' change="change(records)" blur="blur()" keydown="keyDown()" value="value"';
            referHtml += ' keyfield="' + scope.KeyField + '" CodeField="' + scope.CodeField + '" textfield="' + scope.TextField + '"';
            referHtml += ' entityname="' + scope.EntityName + '" windowtitle="' + scope.WindowTitle + '" ';
            referHtml += 'isselect="' + scope.IsSelect + '" isempty="' + scope.IsEmpty.toString() + '" isgrid="true">';
            for(var i=0; i<refDivElement.children.length; i++){
                var column = {};
                var columnDom = refDivElement.children[i];
                var columnHtml = '<RColumn'
                if (columnDom.getAttribute("type") != undefined && columnDom.getAttribute("type").trim() != "") {
                    columnHtml += ' type="' + columnDom.getAttribute("type").trim() + '"';
                    column.Type = columnDom.getAttribute("type").trim();
                }
                if (columnDom.getAttribute("displayname") != undefined && columnDom.getAttribute("displayname").trim() != "") {
                    columnHtml += ' displayname="' + columnDom.getAttribute("displayname").trim() + '"';
                    column.DisplayName = columnDom.getAttribute("displayname").trim();
                }
                if (columnDom.getAttribute("width") != undefined && columnDom.getAttribute("width").trim() != "") {
                    columnHtml += ' width="' + columnDom.getAttribute("width").trim() + '"';
                    column.Width = columnDom.getAttribute("width").trim();
                }
                if (columnDom.getAttribute("valuefield") != undefined && columnDom.getAttribute("valuefield").trim() != "") {
                    columnHtml += ' valuefield="' + columnDom.getAttribute("valuefield").trim() + '"';
                    column.ValueField = columnDom.getAttribute("valuefield").trim();
                }
                if (columnDom.getAttribute("enum") != undefined && columnDom.getAttribute("enum").trim() != "") {
                    columnHtml += ' enum="' + columnDom.getAttribute("enum").trim() + '"';
                    column.Enum = columnDom.getAttribute("enum").trim();
                }
                if (columnDom.getAttribute("round") != undefined && columnDom.getAttribute("round").trim() != "") {
                    columnHtml += ' round="' + columnDom.getAttribute("round").trim() + '"';
                    column.Round = columnDom.getAttribute("round").trim();
                }
                if (columnDom.getAttribute("format") != undefined && columnDom.getAttribute("format").trim() != "") {
                    columnHtml += ' format="' + columnDom.getAttribute("format").trim() + '"';
                    column.Format = columnDom.getAttribute("format").trim();
                }
                if (columnDom.getAttribute("bindfield") != undefined && columnDom.getAttribute("bindfield").trim() != "") {
                    columnHtml += ' bindfield="' + columnDom.getAttribute("bindfield").trim() + '"';
                    column.BindField = columnDom.getAttribute("bindfield").trim();
                }
                columnHtml += '></RColumn>';
                scope.Columns.push(column);

                referHtml += columnHtml;                
            }
            referHtml += '</Refer>';

            $compile(referHtml)(scope, function (clone, scope) {
                    refDivElement.innerHTML = '';
                    refDivElement.appendChild(clone[0]);
                    dataGridCtrl.scope.addColumn(scope, refDivElement);
                }
            );

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isedit"];
                },
                function(){
                    if(attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsEdit = false;
                    }
                    else{
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}])

.directive("dropdownlistcolumn", ['BaseEnum', function(BaseEnum) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            enum: '=?',
            titleclick: '&'
        },
        template:
            '<td ng-show="IsDisplay">' +
                '<div style="display: none">' +
                    '<DropDownList class="GridBaseControl" style="height:100%;" value="value" change="change()" blur="blur()" keydown="keyDown()" enum="enum" isempty="{{scope.IsEmpty.toString()}}"></DropDownList>' + 
                '</div>' +
                '<div style="width: {{DivWidth}}" ng-click="order()">' +
                    '<u ng-if="IsTitleClick" style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                    '<span ng-if="!IsTitleClick">{{DisplayName}}</span>' +
                    '<div class="DT_EmptyDiv" ng-show="!IsEmpty">*</div>' +
                    '<i ng-if="IsOrder">&nbsp;</i>' +
                    '<span ng-if="IsOrder" ng-class="SortClass"/>' +
                '</div>' +
            '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControllType = BaseEnum.ControllType.DropDownList;
            scope.TextAlignClass = 'TextLeftCenter';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.SortValue = BaseEnum.SortType.Empty.Value;
            scope.SortClass = "";
            scope.BindField = "";

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }
            if (attrs["bindfield"] != undefined && attrs["bindfield"].trim() != "") {
                scope.BindField = attrs["bindfield"].trim();
            }

            if(scope.IsOrder && scope.ValueField.indexOf('_') == 0 && 
                dataGridCtrl.scope.module.IsEntityModule && dataGridCtrl.scope.module.LoadMode != BaseEnum.LoadMode.CacheAndNoPaging){
                scope.IsOrder = false;
            }

            if(scope.IsOrder){
                var sortValue = null;
                if(dataGridCtrl.scope.DataGrid_OrderBy && dataGridCtrl.scope.DataGrid_OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.DataGrid_OrderBy[scope.ValueField];
                }
                else if(dataGridCtrl.scope.module.OrderBy && dataGridCtrl.scope.module.OrderBy.hasOwnProperty(scope.ValueField)){
                    sortValue = dataGridCtrl.scope.module.OrderBy[scope.ValueField];
                }
                if(sortValue){
                    var spanElement = element[0].children[1].lastElementChild;
                    scope.SortValue = sortValue;
                    if(sortValue == 1){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(sortValue == -1){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                }
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function(){
                scope.titleclick();
            };

            scope.order = function(){
                if(scope.IsOrder){
                    var spanElement = element[0].children[1].lastElementChild;
                    if(scope.SortValue == BaseEnum.SortType.Empty.Value){
                        scope.SortValue = BaseEnum.SortType.Asc.Value;
                        scope.SortClass = "DT_Order_Asc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Asc.Value){
                        scope.SortValue = BaseEnum.SortType.Desc.Value;
                        scope.SortClass = "DT_Order_Desc";
                    }
                    else if(scope.SortValue == BaseEnum.SortType.Desc.Value){
                        scope.SortValue = BaseEnum.SortType.Empty.Value;
                        scope.SortClass = "";
                    }
                    dataGridCtrl.scope.setOrderBy(scope.ValueField, scope.SortValue);
                    dataGridCtrl.scope.loadByOrder();
                }
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") >= 0){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = record[scope.ValueField];
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = " + scope.value.toString());
                    dataGridCtrl.scope.cellValueChange(scope.ValueField, scope.value, oldValue);
                }
            };
            scope.blur = function(){
                var td = event.srcElement.parentNode;
                element[0].children[0].appendChild(event.srcElement);
                if(scope.value != undefined && scope.value !== "" && scope.value > -1) {
                    var isFind = false;
                    for(var option in scope.enum){
                        if(scope.enum[option].Value == scope.value){
                            isFind = true;
                            td.children[0].innerText = scope.enum[option].Text;
                            td.children[0].setAttribute("title", scope.enum[option].Text);
                            break;
                        }
                    }
                    if(!isFind){
                        td.children[0].innerHTML = '&nbsp;';
                        td.children[0].removeAttribute("title");
                    }
                }
                else{
                    td.children[0].innerHTML = '&nbsp;';
                }
                td.children[0].style.display = '';
            };

            element[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );
            element[0].children[1].addEventListener('mousedown',
                function(){
                    dataGridCtrl.scope._titleMouseDown(element[0].cellIndex);
                },
                false
            );

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isedit"];
                },
                function(){
                    if(attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsEdit = false;
                    }
                    else{
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}])

.directive("htmlcolumn", ['BaseEnum', function(BaseEnum) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
        '<td ng-show="IsDisplay">' +
            '<div style="display: none" ng-transclude>' +
            '</div>' +
            '<!--支持列头点击事件-->' +
            '<div style="width: {{DivWidth}}">' +
                '<u ng-if="IsTitleClick" style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                '<span ng-if="!IsTitleClick">{{DisplayName}}</span>' +
            '</div>' +
        '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.IsDisplay = true;
            scope.ControllType = BaseEnum.ControllType.Html;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.Element = element[0].children[0].children[0];

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function(){
                scope.titleclick();
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 32 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };

            element[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );
            element[0].children[1].addEventListener('mousedown',
                function(){
                    dataGridCtrl.scope._titleMouseDown(element[0].cellIndex);
                },
                false
            );

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}]);

// app.directive('onDataGridBodyLoaded', function ($timeout) {
//     return {
//         restrict: 'A',
//         link: function(scope, element, attr) {
//             if (scope.$last === true) {
//                 $timeout(function() {
//                     scope.$emit('$DataGridBodyLoaded');
//                 });
//             }
//         }
//     };
// });

// app.directive('onDataGridRightLoaded', function ($timeout) {
//     return {
//         restrict: 'A',
//         link: function(scope, element, attr) {
//             if (scope.$last === true) {
//                 $timeout(function() {
//                     scope.$emit('$DataGridRightLoaded');
//                 });
//             }
//         }
//     };
// });
